Reputation: 32776
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.
Upvotes: 1
Views: 676
Reputation: 6612
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/
Upvotes: 1
Reputation: 24472
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(""));
}
Upvotes: 0
Reputation: 414006
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
Upvotes: 4