-2

What is the most efficient / elegant way to iterate object values in JavaScript?

As an example, assume the following object: let myObj = {p1: "v1", p2: "v2"}

Tomas Nikodym
  • 13,210
  • 3
  • 19
  • 18
  • Try searching for "stackoverflow iterate object properties". –  Sep 13 '16 at 06:46
  • @torazaburo I did, and the results are either outdated, incomplete or discuss frameworks. Note that I have also posted answer to my own question in an attempt to summarize the possible solutions in modern ES. – Tomas Nikodym Sep 13 '16 at 07:40
  • http://stackoverflow.com/questions/8312459/iterate-through-object-properties also has useful answers, although some of them are quite deeply buried. –  Sep 13 '16 at 09:12

1 Answers1

1

ECMAScript 2017:

If your target platform supports Object.values:

Object.values(myObj).forEach(value => /* do something */)

If you need the property names as well, you can use Object.entries in combination with array destructuring:

Object.entries(myObj).forEach(([key, value]) => /* do something */)

ECMAScript 5:

If you need to be backwards compatible and don't want to use a polyfill:

Object.keys(myObj).map(prop => myObj[prop]).forEach(value => /* do something */)

Older versions:

Note that the for...in statement iterates over prototype's properties as well, so you need to filter them out using Object.prototype.hasOwnProperty.

for (var key in myObj) {
  if (myObj.hasOwnProperty(key)) {
    var value = myObj[key];
    // do something
  }
}
Tomas Nikodym
  • 13,210
  • 3
  • 19
  • 18
  • 1
    For completeness, also show `for (let [key, value] of Object.entries(myObj))`. –  Sep 13 '16 at 06:33