1

How can I loop through an array of objects?

users = new Array()
users.push({id: "5", name: "solomom"});
users.push({id: "3", name: "jonathan"});
for(u in users){
    alert(u.name);
}

This alerts me with undefined, am I doing something wrong? im really a big newbie in javascript.

unknown
  • 846
  • 3
  • 15
  • 38

4 Answers4

3

Changing it to:

alert(users[u].name);

Would make it alert expected values, because for in loops iterate through the keys of an object, however you should not use for in loops to iterate through arrays in Javascript.

Instead use a regular for loop:

for(var i = 0; i < users.length; i++){
    alert(users[i].name);
}

You should also get in the habit of using console.log to debug rather than alert. It will make debugging much easier when you need it to be.

Paul
  • 139,544
  • 27
  • 275
  • 264
1

You're thinking of for...of

Syntax

for (variable of object)
  statement

Parameters

  • variable - On each iteration a value of a different property is assigned to variable.
  • object - Object whose enumerable properties are iterated.

This isn't supported in most modern browsers.


You'd probably want to use Array.forEach for what you're trying to accomplish.

users.forEach(function(u) {
    alert(u.name);
});
Wex
  • 15,539
  • 10
  • 64
  • 107
0

You should use a regular for loop to loop through arrays. A for-in loop iterates the enumerable properties of an object. An array in JavaScript is technically an object, which is where the problem comes from.

for (var i = 0; i < users.length; ++i)
{
    alert( users[i].name );
}
David G
  • 94,763
  • 41
  • 167
  • 253
0

A for..in loop assigns each key to u, not each value. You would need to do something like
alert(users[u].name)

That being said, NEVER use for..in on an array (unless it's sparse). Instead, do this:

for( i=0, l=users.length; i<l; i++) {
    alert(users[i].name);
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Could you elaborate on why `for..in` is bad practice? – Wex Apr 22 '13 at 04:30
  • 1
    @Wex: This SO has good info on that: [**Why is using “for…in” with array iteration such a bad idea?**](http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-such-a-bad-idea) Bascially when doing `for(u in users){`; Each time the loop is executed, `u` is filled with the name of another property that exists on the object until all properties have been returned. The returned properties are **both** those that exist on the object instance **and** those inherited through the prototype chain. Including objects from the prototype chain can lead to unexpected results. – Nope Apr 22 '13 at 09:27
  • 1
    @Wex: Additionally see [**For...in MDN Documentation**](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...in). Bottom of `Description` Section has a comment on why for..in should not be used to iterate over an Array where index order is important. – Nope Apr 22 '13 at 09:53