Created
January 26, 2012 15:59
-
-
Save mteece/1683473 to your computer and use it in GitHub Desktop.
Quickly iterate an array with objects.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(){ | |
var data = { | |
"GetResult":[ | |
{ | |
"ID":1, | |
"width":150, | |
"height":50 | |
}, | |
{ | |
"ID":2, | |
"width":5, | |
"height":150 | |
}, | |
{ | |
"ID":3, | |
"width":75, | |
"height":30 | |
}, | |
{ | |
"ID":4, | |
"width":25, | |
"height":250 | |
} | |
] | |
} | |
var results = 'GetResult' | |
// Iterate JSON data | |
var len = data[results].length; | |
for (var j = 0; j < len; j++) { | |
var info = data[results][j]; | |
console.log(info.width); | |
} | |
})(); |
So line 35 would be like for (info in data[results])
The object 'data' contains an array of objects in the property 'GetResult'. I thought that was the fastest way to loop it? After I stubbed this out I found later the data was an object (with no array of objects like here) so we went with your suggestion with the for . . . in loop.
Totally confused: looping over an array of objects w/ for ... in should loop over the objects. Looping over an object with for . . . in should give you each of its properties.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
why not just use a for . . . in loop here? That's what it's for, looping over objects.