1

If i have an array of objects, how can i iterate through it?

For example this array

[{ name: "objc1", size: "small" }, { first: "objc2", size: "medium" }, { first: "objc3", size: "Big" }]

I can access each object with this:

for (var key in collection){

  alert(collection[key])  

}

But how can i go inside the object, to each property?

Johannes
  • 59,058
  • 16
  • 59
  • 114

2 Answers2

1

Don' t use for ... in over arrays, this approach has several issues. The for ... in is actually made for iterating over properties. Therefore, use the following (ES6):

for (const item of collection) {
  for (const key in item) {
    alert(key+': '+item[key]);
  }
}

On ES5, you need a loop like this:

var item;
for (var i=0; i < collection.length; i++) {
  item = collection[i];
  for (var key in item) {
    alert(key+': '+item[key]);
  }
}
Community
  • 1
  • 1
Lucero
  • 57,903
  • 8
  • 117
  • 151
0

var collection = [{ name: "objc1", size: "small" }, { first: "objc2", size: "medium" }, { first: "objc3", size: "Big" }];
collection.forEach(item =>{
  for (property in item){
    console.log(item[property]);
  };
});
BrTkCa
  • 4,585
  • 3
  • 23
  • 44