1

I have this issue. I want to iterate through the attributes of a JSON structure, i.e this structure

var txt = '{"employees":{' +
'"p1":{'+
    '"info":{'+
        '"firstName":"John","lastName":"Doe" }},' +
'"p2":{'+
    '"info":{'+
        '"firstName":"Anna","lastName":"Smith" }},' +
'"p3":{'+
    '"info":{'+
        '"firstName":"Peter","lastName":"Jones" }}'+

'}}';

I dont want to do something like

json.employees.p1.info.firstName;

(using the p1) I want to do something like

for(var i = 0; i<3;++i){
    console.log(json.employees.p[i].info.firstName);
}

Does someone know how to do it?

I want to do that because the attribute p can be N not so I can't do p1, p2, p3, p4, ..., p101

2 Answers 2

5

You can access properties of JavaScript objects using bracket notation. It is useful when you have to define property name using variable or expression.

So. for your situation, you could access the properties of employees like this:

json.employees['p'+(i+1)].info.firstName
Sign up to request clarification or add additional context in comments.

Comments

0

You can iterate objects like so:

for (var k in your_object)
    console.log(your_object[k]);

So in your case, to iterate through all P objects:

for (var k in json.employees)
    console.log(json.employees[k]);

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.