How do I loop through or enumerate a JavaScript object?
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
.
You can use the for-in
loop as shown by others. However, you also have to make sure that the key you get is an actual property of an object, and doesn't come from the prototype.
Here is the snippet:
var p = {
"p1": "value1",
"p2": "value2",
"p3": "value3"
};
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + p[key]);
}
}
Under ECMAScript 5, you can combine Object.keys()
and Array.prototype.forEach()
:
var obj = { first: "John", last: "Doe" };
Object.keys(obj).forEach(function(key) {
console.log(key, obj[key]);
});
ES6 adds for...of
:
for (const key of Object.keys(obj)) {
console.log(key, obj[key]);
}
ES2017 adds Object.entries()
which avoids having to look up each value in the original object:
Object.entries(obj).forEach(
([key, value]) => console.log(key, value)
);
Both Object.keys()
and Object.entries()
iterate properties in the same order as a for...in
loop but ignore the prototype chain. Only the object's own enumerable properties are iterated.
Edit: ES2016 → ES6
You have to use the for-in loop
But be very careful when using this kind of loop, because this will loop all the properties along the prototype chain .
Therefore, when using for-in loops, always make use of the hasOwnProperty
method to determine if the current property in iteration is really a property of the object you're checking on:
for (var prop in p) {
if (!p.hasOwnProperty(prop)) {
//The current property is not a direct property of p
continue;
}
//Do your logic with the property here
}
链接地址: http://www.djcxy.com/p/754.html
上一篇: 检查给定的密钥是否已经存在于字典中
下一篇: 如何遍历或枚举JavaScript对象?