组装 tree
需要进行组装数据
const list = [
{ id: 1, parent_id: 0, name: "四川省" },
{ id: 2, parent_id: 0, name: "广东省" },
{ id: 3, parent_id: 0, name: "江西省" },
{ id: 5, parent_id: 1, name: "成都市" },
{ id: 6, parent_id: 5, name: "锦江区" },
{ id: 7, parent_id: 6, name: "九眼桥" },
{ id: 8, parent_id: 6, name: "兰桂坊" },
{ id: 9, parent_id: 2, name: "东莞市" },
{ id: 10, parent_id: 9, name: "长安镇" },
{ id: 11, parent_id: 3, name: "南昌市" },
];
组装方法
function buildTree(list) {
let map = {};
list.forEach(item => {
if (!map[item.id]) {
map[item.id] = item;
}
});
list.forEach(item => {
if (item.parent_id !== 0) {
map[item.parent_id].children
? map[item.parent_id].children.push(item)
: (map[item.parent_id].children = [item]);
}
});
return list.filter(item => {
if (item.parent_id === 0) {
return item;
}
});
}
console.log(buildTree(list));
组装后的结果
[
{
id: 1,
parent_id: 0,
name: "四川省",
children: [
{
id: 5,
parent_id: 1,
name: "成都市",
children: [
{
id: 6,
parent_id: 5,
name: "锦江区",
children: [
{ id: 7, parent_id: 6, name: "九眼桥" },
{ id: 8, parent_id: 6, name: "兰桂坊" },
],
},
],
},
],
},
{
id: 2,
parent_id: 0,
name: "广东省",
children: [
{
id: 9,
parent_id: 2,
name: "东莞市",
children: [{ id: 10, parent_id: 9, name: "长安镇" }],
},
],
},
{
id: 3,
parent_id: 0,
name: "江西省",
children: [{ id: 11, parent_id: 3, name: "南昌市" }],
},
]
平铺 tree
需要平铺开的数据
const tree = [
{
id: 1,
parent_id: 0,
name: "四川省",
children: [
{
id: 5,
parent_id: 1,
name: "成都市",
children: [
{
id: 6,
parent_id: 5,
name: "锦江区",
children: [
{ id: 7, parent_id: 6, name: "九眼桥" },
{ id: 8, parent_id: 6, name: "兰桂坊" },
],
},
],
},
],
},
{
id: 2,
parent_id: 0,
name: "广东省",
children: [
{
id: 9,
parent_id: 2,
name: "东莞市",
children: [{ id: 10, parent_id: 9, name: "长安镇" }],
},
],
},
{
id: 3,
parent_id: 0,
name: "江西省",
children: [{ id: 11, parent_id: 3, name: "南昌市" }],
},
]
平铺方法
let result = [];
function flatTree(nodes, parentId) {
if (!nodes || nodes.length === 0) return [];
nodes.forEach(node => {
result.push({
id: node.id,
parentId: parentId,
name: node.name,
});
return flatTree(node.children, node.id);
});
}
flatTree(tree, 0);
console.log(result);
平铺后的结果
[
{ id: 1, parent_id: 0, name: "四川省" },
{ id: 2, parent_id: 0, name: "广东省" },
{ id: 3, parent_id: 0, name: "江西省" },
{ id: 5, parent_id: 1, name: "成都市" },
{ id: 6, parent_id: 5, name: "锦江区" },
{ id: 7, parent_id: 6, name: "九眼桥" },
{ id: 8, parent_id: 6, name: "兰桂坊" },
{ id: 9, parent_id: 2, name: "东莞市" },
{ id: 10, parent_id: 9, name: "长安镇" },
{ id: 11, parent_id: 3, name: "南昌市" },
];
网友评论