1

I've seen a lot of different ways to access values in an array of objects. One being arr.forEach(Function) in which the function is simply a for...in

But im curious, how come two for...in functions does not work, for example:

[{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }]

(Taken from freeCodeCamp).

This works:

function myFunction (item, index) {

  for( var key in item ) {
    console.log(item[key])
  }
}

arr.forEach(myFunction ( prints all the values fine)

but how come this does not work:

for(key in arr)
{
   for(value in key)
   {
    console.log(key[value];
   }
}

I would think this would work, since we can do arr[key] (and print out the objects in the outer loop, but im not able to access the values this way)

edit:

Sidenote: is it possible for me to print out each sub key/value pair: IE for example on Array index 0 to print out "first: "Romeo" and then "last: "Montague"

msmith1114
  • 2,717
  • 3
  • 33
  • 84
  • 3
    `for/in` should not be used on arrays as they will iterate all properties of the object, including inherited ones. `for/in` should be exclusively used on objects. – Scott Marcus Apr 21 '17 at 18:27
  • Have a look at this http://stackoverflow.com/questions/500504/why-is-using-for-in-with-array-iteration-a-bad-idea for more discussion. – Karl Reid Apr 21 '17 at 18:29

3 Answers3

3

but how come this does not work:

Because key in that case would be a string, not an element of the array.

You shouldn't use for..in to iterate over arrays: MDN.

Newer versions of JavaScript (ECMAScript) provide the ability to use for..of loops, which are perfect for iterating over arrays:

for (var item of arr) {
    console.log(item);
}
JLRishe
  • 99,490
  • 19
  • 131
  • 169
  • Ah, well...is there a way for me to grab a subsection object in the array, for example if I wanted to print out the first key/value pair in the arr index 1: Like printing out: `first: "Romeo"` and then `last: "Montague"` – msmith1114 Apr 21 '17 at 18:38
  • You could just use a regular `for(var i=0; i < arr.length; i++)` and then `if(i > limit) break`. Or use the `for..of` loop and keep a separate iteration count variable. – Karl Reid Apr 21 '17 at 18:46
  • 1
    @msmith1114 Yeah, just get the item at index 1 and print its values: `var idx1 = arr[1]; if (idx1) { for (var key in idx1) { console.log(key, ':', idx1[key]); } }` – JLRishe Apr 21 '17 at 18:48
1

Its not working because key in the second for ... in is dynamic, same reason you can't do item.key in the first example

0

You need to loop over the indices of the array and then over the keys of an item of the array.

var array = [{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }],
    key, index;

for (index = 0; index < array.length; index++) {
   for(key in array[index]) {
      console.log(array[index][key]);
   }
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392