实现将JS的一维数组转换成树结构的方法有多种,下面列举了三种常见的实现方式:
方法一:递归构建树结构
function convertToTree(arr, idProp, parentProp, childProp) {
// 将一维数组转换为map,根据idProp来索引元素
const map = {};
arr.forEach(item => {
map[item[idProp]] = item;
});
// 递归构建树结构
const tree = [];
arr.forEach(item => {
const parent = map[item[parentProp]];
if (parent) {
parent[childProp] = parent[childProp] || [];
parent[childProp].push(item);
} else {
tree.push(item);
}
});
return tree;
}
const arr = [
{ id: 1, name: '节点1', parentId: null },
{ id: 2, name: '节点2', parentId: 1 },
{ id: 3, name: '节点3', parentId: 1 },
{ id: 4, name: '节点4', parentId: 3 },
{ id: 5, name: '节点5', parentId: 2 },
{ id: 6, name: '节点6', parentId: null },
];
const tree = convertToTree(arr, 'id', 'parentId', 'children');
console.log(tree);
方法二:使用迭代方式构建树结构
function convertToTree(arr, idProp, parentProp, childProp) {
// 将一维数组转换为map,根据idProp来索引元素
const map = {};
arr.forEach(item => {
map[item[idProp]] = item;
});
// 迭代构建树结构
const tree = [];
arr.forEach(item => {
const parent = map[item[parentProp]];
if (parent) {
parent[childProp] = parent[childProp] || [];
parent[childProp].push(item);
} else {
tree.push(item);
}
});
return tree;
}
const arr = [
{ id: 1, name: '节点1', parentId: null },
{ id: 2, name: '节点2', parentId: 1 },
{ id: 3, name: '节点3', parentId: 1 },
{ id: 4, name: '节点4', parentId: 3 },
{ id: 5, name: '节点5', parentId: 2 },
{ id: 6, name: '节点6', parentId: null },
];
const tree = convertToTree(arr, 'id', 'parentId', 'children');
console.log(tree);
方法三:使用深度优先搜索(DFS)构建树结构
function convertToTree(arr, idProp, parentProp, childProp) {
// 将一维数组转换为map,根据idProp来索引元素
const map = {};
arr.forEach(item => {
map[item[idProp]] = item;
});
const stack = [];
const tree = [];
// 进行深度优先搜索
arr.forEach(item => {
const parent = map[item[parentProp]];
if (parent) {
parent[childProp] = parent[childProp] || [];
parent[childProp].push(item);
} else {
tree.push(item);
stack.push(item);
}
});
while (stack.length > 0) {
const node = stack.pop();
const children = node[childProp];
if (children) {
children.forEach(child => {
stack.push(child);
child[childProp] = child[childProp] || [];
});
}
}
return tree;
}
const arr = [
{ id: 1, name: '节点1', parentId: null },
{ id: 2, name: '节点2', parentId: 1 },
{ id: 3, name: '节点3', parentId: 1 },
{ id: 4, name: '节点4', parentId: 3 },
{ id: 5, name: '节点5', parentId: 2 },
{ id: 6, name: '节点6', parentId: null },
];
const tree = convertToTree(arr, 'id', 'parentId', 'children');
console.log(tree);