// 扁平数数组转为json树结构
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
},
]
function covert(flatArr) {
var mapTmp = {}
for (var i = 0; i < flatArr.length; i++) {
mapTmp[flatArr[i].id] = flatArr[i]
}
// {1:{id:'',title:'',parent_id:0}}
var reult = []
flatArr.forEach((ele) => {
var parent = mapTmp[ele.parent_id] // 对象{ },parent就是一个地址
if (parent) {
(parent.children || (parent.children = [])).push(ele)
} else {
reult.push(ele)
}
})
return reult
}
console.log('flatArr',covert(flatArr) )
console