封装js方法 构建树结构和扁平化树结构
在JavaScript中,构建树结构和将树结构扁平化是常见的操作。下面我将提供两个方法,一个用于从扁平化的数据中构建树结构,另一个用于将树结构扁平化。
构建树结构
假设我们有一个扁平化的数据列表,每个节点对象包含id
和parentId
属性,我们可以根据这些属性构建树结构。
function buildTree(flatData) {const temp = {};const tree = [];for (const item of flatData) {temp[item.id] = {...item, children: []};}for (const item of flatData) {if (temp[item.parentId]) {temp[item.parentId].children.push(temp[item.id]);} else {tree.push(temp[item.id]);}}return tree;
}
扁平化树结构
如果我们有一个树结构,我们想要将其扁平化,可以使用下面的方法:
方法一:
function flattenTree(tree, parentId = null) {return tree.reduce((acc, node) => {const { children, ...rest } = node;const flattenedNode = { ...rest, parentId };return acc.concat(flattenedNode, flattenTree(children, node.id));}, []);
}
方法二:
function flattenTree(tree, parentId = null) {let flatArray = [];for (const node of tree) {const newNode = {...node, parentId}; // 创建新节点,包含parentIddelete newNode.children; // 删除children属性,因为我们要扁平化flatArray.push(newNode); // 添加到扁平化数组中if (node.children && node.children.length > 0) {// 如果有子节点,递归扁平化子节点flatArray = flatArray.concat(flattenTree(node.children, node.id));}}return flatArray;
}
示例
假设我们有以下扁平化数据:
const flatData = [{ id: 1, name: 'Root', parentId: null },{ id: 2, name: 'Child 1', parentId: 1 },{ id: 3, name: 'Child 2', parentId: 1 },{ id: 4, name: 'Grandchild 1', parentId: 2 },{ id: 5, name: 'Grandchild 2', parentId: 2 },
];
我们可以使用buildTree
方法来构建树结构:
const tree = buildTree(flatData);
console.log(tree);
如果我们有一个树结构:
const treeData = [{id: 1,name: 'Root',children: [{id: 2,name: 'Child 1',children: [{ id: 4, name: 'Grandchild 1' },{ id: 5, name: 'Grandchild 2' },],},{ id: 3, name: 'Child 2' },],},
];
我们可以使用flattenTree
方法来扁平化这个树结构:
const flatDataFromTree = flattenTree(treeData);
console.log(flatDataFromTree);
这两个方法可以相互转换树结构和扁平化数据结构,根据实际需求使用。