# reduce遍历了一个数组，返回的结果不正确

``````{
4:[1,2,4],
5:[1,2,5],
6:[1,3,6],
7:[1,3,7],
}``````

``````{
6:[1,3,6],
7:[1,3,7],
}``````

``````let data = [
{
label: '1231',
value: 1,
children: [
{
label: 'qwe2',
value: 2,
children: [
{
label: 'qwe4',
value: 4,
children: []
},
{
label: 'asd5',
value: 5,
children: []
}
]
},
{
label: 'asd3',
value: 3,
children: [
{
label: 'qwe6',
value: 6,
children: []
},
{
label: 'asd7',
value: 7,
children: []
}
]
}
]
}
]``````
``````function ab(data,resultArray){
return data.reduce((pre,cur)=>{
let tempArray = [...resultArray];
let temp = {...cur};
delete temp.children;
tempArray.push(temp)
return cur.children && cur.children.length > 0
? ab(cur.children,tempArray)
: {...pre,[cur.value]:tempArray}
},{})
}
console.log(ab(data,[]))``````

2 个回答
``````function ab(data, resultArray) {
return data.reduce((pre, cur) => {
let tempArray = [...resultArray];
let temp = { ...cur };
// delete temp.children
tempArray.push(temp.value);
return cur.children && cur.children.length > 0
? { ...pre, ...ab(cur.children, tempArray) }
: { ...pre, [cur.value]: tempArray }
}, {})
}``````

``````let data = [
{
label: '1231',
value: 1,
children: [
{
label: 'qwe2',
value: 2,
children: [
{
label: 'qwe4',
value: 4,
children: []
},
{
label: 'asd5',
value: 5,
children: []
}
]
},
{
label: 'asd3',
value: 3,
children: [
{
label: 'qwe6',
value: 6,
children: []
},
{
label: 'asd7',
value: 7,
children: []
}
]
}
]
}
];
// 获取子节点的value路径
var getlastNodePath = (data,arr=[],res={})=>(data.forEach(item=>(arr.push(item.value),item.children.length > 0 ? (this.getlastNodePath(item.children, arr, res),arr.pop()) : ((res[item.value]=[...arr]),arr.pop()))),res);
getlastNodePath(data);
``````

``````{
4: [1, 2, 4],
5: [1, 2, 5],
6: [1, 3, 6],
}``````

###### 你尚未登录，登录后可以
• 和开发者交流问题的细节
• 关注并接收问题和回答的更新提醒
• 参与内容的编辑和改进，让解决方法与时俱进