JavaScript中如何通过索引路径遍历嵌套数组并查找目标元素
实现方案
1. 原生JavaScript实现
思路:逐个迭代索引路径的每一项,每一步拿到当前层级元素后,若还有后续索引,就将当前元素的children作为下一层的遍历数组,直到走完所有索引即可得到目标元素。
代码实现:
function findByPath(data, path) { let current = data; for (let i = 0; i < path.length; i++) { const index = path[i]; current = current[index]; // 非末尾索引时提前取children数组供下一轮遍历 if (i < path.length - 1) { current = current?.children || []; } } return current; }
测试效果:
console.log(findByPath(data, [2, 1])); // 输出 {text: 'More 2'} console.log(findByPath(data, [2, 2, 1])); // 输出 {text: 'Other-2'}
2. Lodash实现
用lodash没成功通常是没有做路径映射:你给出的索引路径省略了每一层中间的children字段,需要先把原始路径转换为lodash可识别的完整路径,再用_.get方法即可:
// 原始路径转完整路径,比如[2,1] → [2, 'children', 1] function convertPath(originPath) { return originPath.flatMap((item, index) => index === 0 ? [item] : ['children', item] ); } // 调用示例 const target1 = _.get(data, convertPath([2, 1])); const target2 = _.get(data, convertPath([2, 2, 1]));
内容的提问来源于stack exchange,提问作者Rana Imtiaz
相关产品推荐
相关产品推荐

