算法题
已知数据格式,实现一个函数 fn 找出链条中所有的父级id
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| var json = [ { id: '1', name: '广东省', children: [ { id: '11', name: '深圳市', children: [ { id: '111', name: '福田区', children: [] }, { id: '112', name: '龙华区', children: [] } ] } ] } ]
|
1 2 3 4 5
| const value = '112' const fn = (value) => { } fn(value)
|
方法
方法一 递归实现深度遍历,并添加path数组,记录父路径
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| var value = '112'; var fn = (value) => { var stack = json; do { var node = stack.pop();debugger if(node.children.length) { stack.push(...node.children.map(x=>({...x, path: (node.path || node.id) + '-' + x.id}))) } if(node.id === value) { return node.path.split('-') } }while(stack.length) }; fn(value)
|