扁平数组 -> JSON树
let flatArr = [
{ id: 1, title: "title1", parent_id: 0 },
{ id: 2, title: "title2", parent_id: 0 },
{ id: 3, title: "title2-1", parent_id: 2 },
{ id: 4, title: "title3-1", parent_id: 3 },
{ id: 5, title: "title4-1", parent_id: 4 },
{ id: 6, title: "title3-2", parent_id: 3 }
]
const flatArrToJSONTree = arr => {
let map = flatArr.reduce((prev, item) => {
// prev 上一次调用回调返回的值,或初始值
prev[item.id] = item
return prev
}, {})
let result = []
for(let item of arr) {
if(!item.parent_id) { // 一级
result.push(item)
continue
}
// 能到这里 肯定不是第一级
// 先找到父级
if(item.parent_id in map) {
let parent = map[item.parent_id] // 父级
// 经典简洁的有值取值,无值初始化
;(parent.children || (parent.children = [])).push(item)
}
}
return result
}
JSON树 -> 扁平数组
const JSONThreeToFlat = tree => {
return tree.reduce((prev, item) => {
const { children = [], ...rest } = item
return prev.concat( [{...rest}], JSONThreeToFlat(children) )
}, [])
}