JavaScript如何获取嵌套对象的完整索引路径?
如何从嵌套数组中根据ID获取完整层级索引路径
问题描述
我有一个嵌套结构的数组,每个元素可能包含children子数组,现在需要实现一个函数getFullIndexOfObject,传入目标ID后返回对应的层级索引路径(索引从1开始计数)。例如:
- 传入
'item1'返回'1' - 传入
'item1-2'返回'1-2' - 传入
'item2'返回'2'
注意:不能通过解析ID字符串来实现,因为实际场景中ID是随机字符串,和层级无关。
我尝试过的方法
我尝试先获取目标节点的深度,再按深度递归遍历,但始终无法正确收集父级的索引,没法拼接出完整路径。以下是我写的部分代码:
const items = [ { id: 'item1', children: [ { id: 'item1-1', children: [ { id: 'item1-1-1' }, { id: 'item1-1-2' }, { id: 'item1-1-3', children: [ { id: 'item1-1-3-1'} ] }, ] }, { id: 'item1-2', children: [ { id: 'item1-2-1' } ] } ] }, { id: 'item2' } ]; // 获取目标节点的深度 var depth = 0; function getDepthOfId(object, id) { var level; if (object.id === id) return 1; object.children && object.children.some(o => level = getDepthOfId(o, id)); return level && level + 1; } depth = getDepthOfId(items[0], 'item1-1'); console.log('depth === ', depth); // 尝试收集索引栈 var indexStacks = []; function getNestedIndexOfId(obj, id, index) { if (obj.id === id) { indexStacks = [index, ...indexStacks] return index; } if (obj.children) { depth++; obj.children.map((child, i) => { getNestedIndexOfId(child, id, i) }) } } // 还尝试写获取父ID的函数,但没成功 function getParentId(obj, id){ // ...? var parentId; return parentId; } for(var i=0; i<depth; i++){ getNestedIndexOfId('...') } // 期望最终通过indexStacks.join('-')得到路径
现在卡在无法正确收集从根到目标节点的所有索引,求可行的解决方案。
内容的提问来源于stack exchange,提问作者ton1
相关产品推荐
相关产品推荐

