我正在尝试迭代嵌套对象以检索由字符串标识的特定对象。在下面的示例对象中,标识符字符串是“label”属性。我无法理解如何向下迭代树以返回适当的对象。任何帮助或建议将不胜感激。
var cars = {
label: 'Autos',
subs: [
{
label: 'SUVs',
subs: []
},
{
label: 'Trucks',
subs: [
{
label: '2 Wheel Drive',
subs: []
},
{
label: '4 Wheel Drive',
subs: [
{
label: 'Ford',
subs: []
},
{
label: 'Chevrolet',
subs: []
}
]
}
]
},
{
label: 'Sedan',
subs: []
}
]
}
最佳答案
2023 年更新:
很多人询问过非递归方法,所以这里是:
const iterate = (obj) => {
const stack = [obj];
while (stack?.length > 0) {
const currentObj = stack.pop();
Object.keys(currentObj).forEach(key => {
console.log(`key: ${key}, value: ${currentObj[key]}`);
if (typeof currentObj[key] === 'object' && currentObj[key] !== null) {
stack.push(currentObj[key]);
}
});
}
};
带有递归的原始答案
如果您想要深度迭代每个键和值的复杂(嵌套)对象,您可以使用 Object.keys() 来实现。 ,递归:
const iterate = (obj) => {
Object.keys(obj).forEach(key => {
console.log(`key: ${key}, value: ${obj[key]}`)
if (typeof obj[key] === 'object' && obj[key] !== null) {
iterate(obj[key])
}
})
}
关于javascript - 迭代嵌套的 JavaScript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57785941/