How do I loop through or enumerate a JavaScript object? -
i have javascript object following:
var p = { "p1": "value1", "p2": "value2", "p3": "value3" };
now want loop through p
elements (p1
,p2
,p3
...) , keys , values. how can that?
i can modify javascript object if necessary. ultimate goal loop through key value pairs , if possible want avoid using eval
.
you can use for-in
loop shown others. however, have make sure key actual property of object, , doesn't come prototype.
here snippet:
var p = { "p1": "value1", "p2": "value2", "p3": "value3" }; (var key in p) { if (p.hasownproperty(key)) { console.log(key + " -> " + p[key]); } }
Comments
Post a Comment