Skip to content

Instantly share code, notes, and snippets.

@mteece
Created January 26, 2012 15:59
Show Gist options
  • Save mteece/1683473 to your computer and use it in GitHub Desktop.
Save mteece/1683473 to your computer and use it in GitHub Desktop.
Quickly iterate an array with objects.
(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);
}
})();
@tclancy
Copy link

tclancy commented Jan 26, 2012

why not just use a for . . . in loop here? That's what it's for, looping over objects.

@tclancy
Copy link

tclancy commented Jan 26, 2012

So line 35 would be like for (info in data[results])

@mteece
Copy link
Author

mteece commented Jan 26, 2012

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.

@tclancy
Copy link

tclancy commented Jan 26, 2012

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