-1

I'm obviously not understanding how forEach works in JavaScript, because when I run the following code, I don't get any output at all. What am I misunderstanding or doing wrong? Thanks!

var id = [];
id['battery'] = [];
id['battery']['garage'] = 27;
id['battery']['attic'] = 88;
id['battery']['basement'] = 74;
id['battery']['office'] = 62;
id['battery']['hallway'] = 84;

id['battery'].forEach(function(value, room) {
    console.log("value = " + value + " | room = " + room);
});
swmcdonnell
  • 1,381
  • 9
  • 22
  • 1
    `forEach` only iterates over the keys of the array which are positive integers. – 4castle Feb 16 '17 at 19:45
  • JavaScript doesn't have associative arrays; `.forEach()` only iterates through integer-indexed properties. – Pointy Feb 16 '17 at 19:45
  • Possible duplicate of [Iterate through object properties](http://stackoverflow.com/questions/8312459/iterate-through-object-properties) – 4castle Feb 16 '17 at 19:49
  • Thank you. I know it was a dumb question, but I've been switching between PHP and JavaScript and was temporarily confused. – swmcdonnell May 08 '18 at 22:06

1 Answers1

2

You can't use forEach with objects. But you can do this:

var id = {
  battery: {
    garage: 27,
    attic: 88,
    basement: 74,
    office: 62,
    hallway: 84
  }
};

for(var room in id.battery) {
    console.log("value = " + id.battery[room] + " | room = " + room);
};
Antonio
  • 901
  • 5
  • 12