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

如何实现嵌套对象数组中目标ID的索引路径查找

多层嵌套数组中根据ID查找索引路径

给定一个包含多层嵌套对象的数组结构,需要实现一个函数,根据指定的目标ID,返回该对象在嵌套数组中的索引路径。以下是示例结构和预期输出:

示例数据

const dataList = [
  [
      [{id: 100,name: 'Test1'}, {id: 120, name: 'Test12'}],
      [{id: 101,name: 'Test1'}, {id: 121, name: 'Test12'}],
      [{id: 102,name: 'Test1'}, {id: 122, name: 'Test12'}],
      [
        [{id: 103,name: 'Test1'}, {id: 123, name: 'Test12'}],
        [{id: 104,name: 'Test1'}, {id: 124, name: 'Test12'}],
        [{id: 105,name: 'Test1'}, {id: 125, name: 'Test12'}],
      ]
  ],
  [{id: 2,name: 'Test2'}, {id: 13, name: 'Test13'}],
  [{id: 3,name: 'Test3'}, {id: 14, name: 'Test14'}],
  [{id: 4,name: 'Test4'}, {id: 15, name: 'Test15'}],
  [{id: 5,name: 'Test5'}, {id: 16, name: 'Test16'}],
  [{id: 6,name: 'Test6'}, {id: 17, name: 'Test17'}],
  [{id: 7,name: 'Test7'}, {id: 18, name: 'Test18'}],
  [{id: 8,name: 'Test8'}, {id: 19, name: 'Test19'}],
];

预期输出

findIndexPath(dataList, 104); // 输出: [0, 3, 1, 0]
findIndexPath(dataList, 16);  // 输出: [4, 1]

函数实现

我们可以用递归遍历的方式处理任意层级的嵌套结构,核心思路是遍历每个元素,遇到数组就继续递归探索,遇到对象则检查ID是否匹配:

function findIndexPath(list, targetId) {
  // 递归辅助函数,传入当前数组和已记录的路径
  function traverse(arr, path) {
    for (let i = 0; i < arr.length; i++) {
      const current = arr[i];
      // 如果当前元素是数组,继续递归,路径添加当前索引
      if (Array.isArray(current)) {
        const result = traverse(current, [...path, i]);
        // 如果找到结果,直接返回
        if (result) return result;
      } 
      // 如果是对象且ID匹配,返回完整路径
      else if (current?.id === targetId) {
        return [...path, i];
      }
    }
    // 遍历完当前数组没找到,返回null
    return null;
  }

  return traverse(list, []);
}

代码说明

  1. 递归遍历:通过内部辅助函数traverse处理嵌套数组,每次递归传递当前的索引路径
  2. 路径记录:每次进入子数组时,将当前索引加入路径数组,保证路径的正确性
  3. 终止条件:
    • 找到匹配ID的对象时,返回拼接好的完整路径
    • 遍历完当前层级所有元素仍未找到,返回null
  4. 处理任意层级:无论嵌套多少层,递归都会逐层探索,直到找到目标或遍历完成

测试验证

运行以下代码可以验证结果:

console.log(findIndexPath(dataList, 104)); // [0, 3, 1, 0]
console.log(findIndexPath(dataList, 16));  // [4, 1]
console.log(findIndexPath(dataList, 100)); // [0, 0, 0]
console.log(findIndexPath(dataList, 19));  // [7, 1]

内容的提问来源于stack exchange,提问作者ciaksoy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 09:41:29