views:

73

answers:

3

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.

+4  A: 

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

Pointy
yeah, that seems right, Pointy. Oscaar, why format your JSON like that, by the way? Why not { {name: 'Oscar', age: 24}, {name: 'Bill', age: 25} ...}
Hugo Estrada
It's for a sort of DB JSON using localStorage. I want to store "rows and columns" rather than sets of objects. Id normally do it your way tho.
Oscar Godson
A: 
       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(""));
        }
naikus
+1  A: 

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/

yilmazhuseyin
awh, interesting, how would I look through this?
Oscar Godson