简体   繁体   中英

How do I loop through a JSON object that contains arrays?

How would I loop through this correctly?

{names:['oscar','bill','brad'],ages:['20','25','18']}

So i'd basically get the output:

names: oscar
ages: 20

names: bill
ages: 25

names: brad
ages: 18

Yes I know its a for...in loop but I just can't figure out how to get this output.

maybe

for (var i = 0, len = obj.names.length; i < len; ++i) {
  var name = obj.names[i];
  var age = obj.ages[i];
  // ... whatever
}

where "obj" is your JSON object

Just a simple suggestion. It seems to me, implementation bellow would be better for you

{ people:[{name:'oscar',age:20},{...},{...}] } 

To loop through this

var a = { people:[{name:'oscar',age:20}] };
var array = a.people
for(element in array){
 console.log(array[element].name + ',' + array[element].age);
}

we have our main object in variable a and inside we have our array in people attribute of our object. Array have our person objects inside. so first person in our list is a.people[0].name does that help? as you need to use closure with this array you can check this blog post. http://yilmazhuseyin.wordpress.com/2010/07/19/closure-in-javascript-part-3/

       var data = {names:['oscar','bill','brad'],ages:['20','25','18']}
        function loop()   {
           var arrNames = data.names;
           var ages = data.ages;

           var str = [];
           for(var i = 0, len = arrNames.length; i < len; i++)   {
              str.push("\nnames: " + arrNames[i]  + "\nages:" + ages[i]);
           }

           alert(str.join(""));
        }

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