平层数据转树形数据
以下是一个使用JavaScript实现将平层数据转换为树型结构数据的示例函数:
function flatToTree(flatData, idKey, parentKey, childrenKey) {
const tree = [];
const map = {
};
// 将所有节点存储到map中
flatData.forEach(node => {
map[node[idKey]] = node;
node[childrenKey] = [];
});
// 遍历所有节点,将其添加到对应的父节点下
flatData.forEach(node => {
const parent = map[node[parentKey]];
if (parent) {
parent[childrenKey].push(node);
} else {
tree.push(node);
}
});
return tree;
}
该函数接受四个参数:
flatData
:平层数据,即一个包含所有节点的数组。idKey
:节点ID的键名。parentKey
:父节点ID的键名。childrenKey
:子节点数组的键名。
函数首先创建一个空的树型结构数组 tree
和一个空的节点映射对象 map
。然后遍历所有节点,将其存储到 map
中,并为每个节点添加一个空的子节点数组。接着再次遍历所有节点,将其添加到对应的父节点下,如果没有父节点,则将其添加到 tree
数组中。最后返回 tree
数组即可。
使用示例:
const flatData = [
{
id: 1, name: 'Node 1', parentId: null },
{
id: 2, name: 'Node 2', parentId: 1 },
{
id: 3, name: 'Node 3', parentId: 1 },
{
id: 4, name: 'Node 4', parentId: 2 },
{
id: 5, name: 'Node 5', parentId: 2 },
{
id: 6, name: 'Node 6', parentId: 3 },
{
id: 7, name: 'Node 7', parentId: null },
];
const treeData = flatToTree(flatData, 'id', 'parentId', 'children');
console.log(treeData);
输出结果:
[
{
"id": 1,
"name": "Node 1",
"parentId": null,
"children": [
{
"id": 2,
"name": "Node 2",
"parentId": 1,
"children": [
{
"id": 4,
"name": "Node 4",
"parentId": 2,
"children": []
},
{
"id": 5,
"name": "Node 5",
"parentId": 2,
"children": []
}
]
},
{
"id": 3,
"name": "Node 3",
"parentId": 1,
"children": [
{
"id": 6,
"name": "Node 6",
"parentId": 3,
"children": []
}
]
}
]
},
{
"id": 7,
"name": "Node 7",
"parentId": null,
"children": []
}
]
树形数据转平层数据
以下是一个使用递归方式将树型结构数据转为平层数据的JavaScript函数:
function flattenTreeData(treeData, parentId = null, result = []) {
treeData.forEach(node => {
const {
id, children, ...rest } = node;
result.push({
id, parentId, ...rest });
if (children) {
flattenTreeData(children, id, result);
}
});
return result;
}
该函数接受三个参数:
treeData
:树型结构数据,必须是一个数组。parentId
:当前节点的父节点ID,初始值为null
。result
:用于存储平层数据的数组,初始值为[]
。
函数首先遍历树型结构数据的每个节点,将其转为平层数据格式,并将其添加到result
数组中。然后,如果该节点有子节点,就递归调用flattenTreeData
函数,将子节点也转为平层数据格式并添加到result
数组中。
最后,函数返回result
数组,其中包含了所有节点的平层数据格式。