I have a JavaScript object like the following:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
Now I want to loop through all p
elements (p1
, p2
, p3
...) And get their keys and values. How can I do that?
I can modify the JavaScript object if necessary. My ultimate goal is to loop through some key value pairs and if possible I want to avoid using eval
.
The
Object.keys()
method returns an array of a given object's own enumerable properties. Read more about it hereSo it gives the same list of keys as you intend by testing each object key with hasOwnProperty. You don't need that extra test operation than and
Object.keys( obj ).forEach(function( key ){})
is supposed to be faster. Let's prove it:In my Firefox I have following results
PS. on Chrome the difference even bigger http://codepen.io/dsheiko/pen/JdrqXa
PS2: In ES6 (EcmaScript 2015) you can iterate iterable object nicer:
In latest ES script, you can do something like this:
via prototype with forEach() which should skip the prototype chain properties:
Note: you can do this over arrays, but you'll iterate over the
length
and other properties, too.Object.entries()
function: