在 ES6/2015 中,您可以循环访问这样的对象(使用 arrow function):
Object.keys(myObj).forEach(key => {
console.log(key); // the name of the current key.
console.log(myObj[key]); // the value of the current key.
});
JS Bin
在 ES7/2016 中,您可以使用 Object.entries 代替 Object.keys 并像这样循环访问对象:
Object.entries(myObj).forEach(([key, val]) => {
console.log(key); // the name of the current key.
console.log(val); // the value of the current key.
});
以上内容也可以作为单线:
Object.entries(myObj).forEach(([key, val]) => console.log(key, val));
jsbin
如果您还想循环遍历嵌套对象,可以使用 recursive 函数 (ES6):
const loopNestedObj = obj => {
Object.keys(obj).forEach(key => {
if (obj[key] && typeof obj[key] === "object") loopNestedObj(obj[key]); // recurse.
else console.log(key, obj[key]); // or do something with key and val.
});
};
JS Bin
与上面的函数相同,但使用 ES7 Object.entries() 而不是 Object.keys():
const loopNestedObj = obj => {
Object.entries(obj).forEach(([key, val]) => {
if (val && typeof val === "object") loopNestedObj(val); // recurse.
else console.log(key, val); // or do something with key and val.
});
};
在这里,我们使用Object.entries() 结合Object.fromEntries() 循环遍历嵌套对象更改值并返回一个新对象(ES10/2019):
const loopNestedObj = obj =>
Object.fromEntries(
Object.entries(obj).map(([key, val]) => {
if (val && typeof val === "object") [key, loopNestedObj(val)]; // recurse
else [key, updateMyVal(val)]; // or do something with key and val.
})
);
循环对象的另一种方法是使用 for ... in 和 for ... of。见vdegenne's nicely written answer。