You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 19:57:04