1

I've got this:

var JSON = [
    {
        "id": 1,
        "name1": "Seymore Butts",
        "name2": "Jane Doe",
        "name3": "John Smith",
        "name4": "Mike Hawk"
    }];
for (i = 1; i < 5; i++) {
    var index = "name" + i;
    window.console.log(JSON[0].index);
}

and of course it's getting undefined because it's looking for

JSON[0].index 

instead of

JSON[0].name1 

Any way to force it to evaluate the index var instead of just reading "index"?

fassetar
  • 615
  • 1
  • 10
  • 37
JohnC
  • 97
  • 4
  • 5
    For future reference, you have an array of *javascript objects*, not *JSON* (which is always, by definition, a string) – jbabey Aug 02 '13 at 17:43
  • 2
    possible duplicate of [JavaScript object: access variable property by name as string](http://stackoverflow.com/questions/4255472/javascript-object-access-variable-property-by-name-as-string), http://stackoverflow.com/questions/3153969/create-object-using-variables-for-property-name, http://stackoverflow.com/questions/2241875/how-to-create-object-property-from-variable-value-in-javascript, http://stackoverflow.com/questions/4694652/javascript-creating-object-and-using-variable-for-property-name, etc... – jbabey Aug 02 '13 at 17:44

2 Answers2

4

Yup, just change your syntax to:

window.console.log(JSON[0][index]);
Kyle Fransham
  • 1,859
  • 1
  • 19
  • 22
2

Use this:

for (i = 1; i < 5; i++) {
    var index = "name" + i;
    window.console.log(JSON[0][index]);
}

The difference between . and [] here is that object.sub_field will try to access field named sub_field, while object[sub_field] will try to access field named by "whatever is in variable sub_field".

mishik
  • 9,973
  • 9
  • 45
  • 67