扁平数组 转 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-1', parent_id: 2 },
]
function convert (list) {
const result = [];
const map = list.reduce((pre,cur) => {
pre[cur.id] = cur;
return pre
}, {})
// 1: {id: 1, title: '标题1', parent_id: 0}
// 2: {id: 2, title: '标题2', parent_id: 0}
// 3: {id: 3, title: '标题2-1', parent_id: 2}
// 4: {id: 4, title: '标题3-1', parent_id: 3}
// 5: {id: 5, title: '标题4-1', parent_id: 4}
// 6: {id: 6, title: '标题2-1', parent_id: 2}
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.children = parent.children || []
parent.children.push(item)
}
}
return result
}
console.log(convert(flatArr));
运行结果
标签:pre,parent,title,树结构,标题,item,JSON,数组,id 来源: https://blog.csdn.net/weixin_46874084/article/details/122752913