Iterating over object values in JavaScript -
this question has answer here:
what efficient / elegant way iterate object values in javascript?
as example, assume following object: let myobj = {p1: "v1", p2: "v2"}
ecmascript 2017:
if target platform supports object.values:
object.values(myobj).foreach(value => /* */)
if need property names well, can use object.entries in combination array destructuring:
object.entries(myobj).foreach(([key, value]) => /* */)
ecmascript 5:
if need backwards compatible , don't want use polyfill:
object.keys(myobj).map(prop => myobj[prop]).foreach(value => /* */)
older versions:
note for...in statement iterates on prototype's properties well, need filter them out using object.prototype.hasownproperty.
for (var key in myobj) { if (myobj.hasownproperty(key)) { var value = myobj[key]; // } }
Comments
Post a Comment