首页 > 解决方案 > 如何根据javascript中数组中的路径遍历嵌套对象?

问题描述

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'

给定第一个输入作为嵌套对象,第二个输入作为包含字符串的数组。根据数组设置的路径遍历嵌套对象以输出“完成”的最佳方法是什么?

标签: javascriptarraysobject

解决方案


您可以reduce使用数组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']));


推荐阅读