How do I loop an array of objects and return it’s value inside the array?

  arrays, javascript

For some reason it’s returning both the key and value an excessive number of times. What am I doing wrong?

function loopAnArrayOfObjects(arrayOfObjects) {
  for (var i = 0; i < arrayOfObjects.length; i++) {
      for (var key in arrayOfObjects) {
          console.log(arrayOfObjects[key]);
      }
  }
}

loopAnArrayOfObjects([{a: 1, b: 2}, {z: 5, y: 6}, {q: 14} ]);
// expected console output:
  // 1
  // 2
  // 5
  // 6
  // 14

loopAnArrayOfObjects([{queue: false, stack: true}, {fish: 'swims'}, {shirt: 's', pop: 'p', eye: 'e'} ]);
// expected console output:
  // false
  // true
  // swims
  // s
  // p
  // e

Source: Ask Javascript Questions

LEAVE A COMMENT