1

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.

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

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} ...}
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.
1

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/

1 Comment

awh, interesting, how would I look through this?
0
       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(""));
        }

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.