0

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 ?

1
  • I've edited out the "JSON" term from your question. JSON implies a string: if you can loop it with a for() construct, it can't be a string. Commented Aug 29, 2013 at 8:24

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

To clarify: the document object is part of the DOM so it's used to manipulate HTML documents, not JavaScript objects.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.