扁平数组转tree
需要用到的测试数据
let flatArr = [
{ id:1, title:'标题1', parent_id:0 },
{ id:2, title:'标题2', parent_id:0 },
{ id:3, title:'标题2-1', parent_id:2 },
{ id:4, title:'标题3-1', parent_id:3 },
{ id:5, title:'标题4-1', parent_id:4 },
{ id:6, title:'标题2-2', parent_id:2 },
]
使用 reduce 实现
const convert = (list)=>{
const result = []
const map = list.reduce((pre,cur)=>{
pre[cur.id] = cur
return pre
},{})
for(let item of list){
if(item.parent_id === 0){
result.push(item)
continue
}
if(item.parent_id in map){
const parent = map[item.parent_id]
parent.childer = parent.childer || []
parent.childer.push(item)
}
}
return result
}
const res = convert(flatArr)
console.time()
console.log(convert(flatArr));
console.timeEnd()
使用 filter 实现
const convert2 = (list)=>{
const result = []
list.forEach(r => {
r.childer = list.filter(re=> re.parent_id === r.id)
if(r.parent_id === 0){
result.push(r)
}
});
return result
}
console.time()
console.log(convert2(flatArr));
console.timeEnd()
Tree 转 扁平化数组
const flatten = (arr)=>{
return arr.reduce((pre,cur)=>{
const {id,title,parent_id,childer = []} = cur
return pre.concat([{id,title,parent_id}], flatten(childer))
},[])
}
console.log(flatten(res));
标签:const,parent,title,list,tree,扁平,数组,console,id
From: https://www.cnblogs.com/ymscq/p/17103736.html