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"}
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"}
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
}
}