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"?

2

2 Answers 2

4

Yup, just change your syntax to:

window.console.log(JSON[0][index]);
Sign up to request clarification or add additional context in comments.

Comments

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".

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.