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?
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 :
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] );
}
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
.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With