简体   繁体   中英

How do I iterate on a JSON file with javascript?

I have this issue. I want to iterate through the attributes of a JSON structure, ie 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

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

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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM