在TypeScript中查找数组深层嵌套对象的索引路径问题
问题排查与修复
你的代码返回false的核心问题在于递归逻辑的路径收集方式和返回值处理不当,具体问题点和修复方案如下:
原代码问题分析
- 逻辑与运算符的误用:
return index !== -1 && [index, ...(inner || [])]中,当递归未找到结果时会返回false,导致上层findIndex误判当前元素不匹配,最终整个函数返回false而非预期的索引路径。 - 递归回调的逻辑混乱:
findIndex的回调中直接返回递归结果,这种方式会将递归返回的数组(真值)视为当前元素匹配成功,虽然能找到索引,但路径收集的逻辑不够清晰,容易出现层级错误。
修复后的代码
const field = { id: "field-e656ba1c-2b18-4dfd-b582-03f1fbfc5642", type: "field", key: "testKey", } const layout = [ { id: "section-766f11d4-c97c-4d5e-8dca-3bf5a2c0356e", type: 'section', children: [ { id: "row-54eed1fd-0592-4196-bbff-e0befd65db41", type: "row", children: [ { id: "column-4d9844ea-19c9-454f-b2f0-17a63f6d2f1e", type: "column", children: [{ id: "field-e656ba1c-2b18-4dfd-b582-03f1fbfc5642", type: "field", key: "testKeys", }], }, ], } ] }, { id: "section-766f11d4-c97c-4d5e-8dca-3bf5a2c0356e", type: 'section', children: [ { id: "row-54eed1fd-0592-4196-bbff-e0befd65db41", type: "row", children: [ { id: "column-4d9844ea-19c9-454f-b2f0-17a63f6d2f1e", type: "column", children: [field], }, ], } ] } ] const findIdx = (array, fieldKey) => { const find = (arr) => { // 非数组直接返回null,终止递归 if (!Array.isArray(arr)) return null; // 遍历当前数组的每个元素 for (let i = 0; i < arr.length; i++) { const item = arr[i]; // 当前元素匹配目标key,返回当前索引的数组 if (item.key === fieldKey) { return [i]; } // 元素有children属性,递归查找子层级 if (item.children) { const childPath = find(item.children); // 子层级找到路径,将当前索引拼接到路径最前面 if (childPath) { return [i, ...childPath]; } } } // 遍历完未找到,返回null return null; }; const result = find(array); // 可选:返回数组格式或字符串格式 return result ? result : null; // 如果需要字符串格式,替换为:return result ? result.join('-') : null; } console.log('path: ', findIdx(layout, 'testKey')); // 输出: path: [1, 0, 0, 0]
修复逻辑说明
- 明确递归终止条件:非数组输入直接返回
null,避免无效递归。 - 遍历+递归的清晰逻辑:逐个遍历数组元素,先判断当前元素是否匹配,匹配则返回当前索引;不匹配则递归查找其子层级,找到子路径后将当前索引前置,形成完整路径。
- 明确返回值语义:找到路径返回数组(或字符串),未找到返回
null,避免返回false导致的语义混淆。
内容的提问来源于stack exchange,提问作者Nick
相关产品推荐
相关产品推荐

