Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over array of objects javascript - odd behaviour?

Tags:

javascript

var myArr = [{a:1, b:2}, {c:3, d:4}];

for (var item in myArr) {
    console.log(item);
}

Item returns the key (ex: 0, 1) instead of the object itself. Why?

like image 367
Andy Hin Avatar asked Jul 03 '11 20:07

Andy Hin


4 Answers

Douglas Crockford recommends in JavaScript: The Good Parts to avoid using the for in statement.

If you use for in to loop over property names in an object, the results are not ordered.

The for in loop is best for iterating over name-value pairs, and the for each loop best for iterating over values i.e arrays.

E.g,

var o = {'name':'Batman', 'age':33, 'city':'Gotham City'};
   for (var p in o) {
        console.log(p+': '+o[p]);
    }

There’s no way we can get the property name if we were to use the For Each Loop for the above object.


Note :

  1. The For in Loop is best for name-value pairs.
  2. The For Each Loop is best for iterable values. Eg: arrays, and objects if you are not interested in the name of the property.
like image 85
Saurabh Gokhale Avatar answered Oct 16 '22 23:10

Saurabh Gokhale


Javascript for..in loops always return the index/name, not the value. To get what you want, you should use:

var myArr = [{a:1, b:2}, {c:3, d:4}];

for (var index in myArr) {
    console.log( myArr[index] );
}

However, as said before, the for..in statement should be use with caution, and it is not intended to be used with an array. You should use a for loop instead

var myArr = [{a:1, b:2}, {c:3, d:4}];

for( var i=0, l=myArr.length; i<l; i++ ) {
    console.log( myArr[i] );
}
like image 42
pomeh Avatar answered Oct 16 '22 23:10

pomeh


The for ... in loop iterates over the keys (properties) of an object.
It is not intended to be used for arrays.

It will also iterate over properties inherited from the object's prototype.

like image 3
SLaks Avatar answered Oct 16 '22 22:10

SLaks


Adding an answer here to accommodate the latest ECMAScript 6 standard.

Check out this page for a great read with examples.

And a rather tasty caveat: this awesome new functionality will work with nearly ever iterable object! From MDN:

The for...of statement creates a loop iterating over iterable objects (including Array, Map, Set, String, TypedArray, arguments object and so on)...

So for example, you could use:

for (let item of myArr) {
    console.log(item);
} 

Although to super clear that you are logging an object, I would be a bit nicer to the next person to read your code by renaming "item" to "obj", producing this:

for (let obj of myArr) {
    console.log(obj);
} 

Why rename the variable? Well, although we use the term 'item' to denote any generic item in an array, your array only contains objects. If you know, or expect, this array to only every contain objects, you could name the variable based on the type of item (i.e. an object) the array contains.

Happy coding!

like image 1
GrayedFox Avatar answered Oct 16 '22 23:10

GrayedFox