GuybrushThreepwood
GuybrushThreepwood

Reputation: 5616

Accessing JavaScript object via key

I have a JavaScript object called data. I am using the following code to sort the keys in the object :

var index = [];

// build the index
for (var x in data) {
    index.push(x);
}

// sort the index
index.sort(function (a, b) {
    return a == b ? 0 : (a > b ? 1 : -1);
});

I then want to access the value for a particular index key in the following way :

for (var i=0; i<index.length; i++) {
    var key = index[i];
    document.getElementById(key).value = data.key;
}

However I am getting undefined for the data.key value. Can anyone suggest why ?

Upvotes: 0

Views: 95

Answers (2)

Sirko
Sirko

Reputation: 74036

Change to

document.getElementById(key).value = data[key];

If the key you want to access is stored within a variable, you have to use the bracket notation. In your code, JavaScript will search for a key named "key" and thus fails.

Example:

var key = 'test';

console.log( data.key );  // yields content of data.key
console.log( data[key] ); // yields content of data.test

Upvotes: 3

Sgoldy
Sgoldy

Reputation: 796

How about

Object.keys(data)[key] ?

Not sure it would work, without showing the structure of data.

edit: This way retrieves object key according to numerical index (0,1...,n), and not by name.

Upvotes: 0

Related Questions