const obj = {
first: { second: { third: 'done'} },
hello: { world: { foo: { bar: 'wrong' } } },
second: { third: 'wrong'}
};
const arr = [ 'first', 'second', 'third' ];
function traverse(obj, arr) {
}
// output = 'done'
给定第一个输入作为嵌套对象,第二个输入作为包含字符串的数组,根据数组设置的路径遍历嵌套对象以输出 done
的最佳方法是什么?
最佳答案
您可以减少
数组arr
,在每一步将累加器更改为更深的对象。
const obj = {
first: { second: { third: 'done'} },
hello: { world: { foo: { bar: 'wrong' } } },
second: { third: 'wrong'}
};
const arr = [ 'first', 'second', 'third' ];
function traverse(obj, arr) {
return arr.reduce((acc, curr) => acc ? acc[curr] : undefined, obj);
}
console.log(traverse(obj, arr));
console.log(traverse(obj, ['hello', 'world', 'foo']));
console.log(traverse(obj, ['first', 'hello', 'world']));
关于javascript - 如何在javascript中根据数组中的路径遍历嵌套对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58314552/