javascript - 如何根据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'
给定第一个输入作为嵌套对象,第二个输入作为包含字符串的数组。根据数组设置的路径遍历嵌套对象以输出“完成”的最佳方法是什么?
解决方案
您可以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']));
推荐阅读
- java - 尝试访问 AWS 服务时出现不支持的记录版本 Unknown-0.0 异常
- mysql - SQL:在另一个表中查找值并更新它们
- reactjs - 使用钩子生成一个列表,其中包含从画廊或相机中挑选的图像
- r - 在 R 中读取文本文件
- xml - 如何在 Odoo 12 中为表单域创建动态标签?
- scala - 使用 Spark/Scala,有没有办法加入复杂的数据结构?
- windows - Powershell 脚本 - 中断循环
- javascript - React 路由器不更新子组件参数
- python - 如何通过 Dart/Flutter 中的主机名获取本地连接设备的 IP 地址?
- java - yaml中的Java liquibase变量