当前位置:网站首页>JS从扁平array转tree
JS从扁平array转tree
2022-08-02 03:34:00 【IICOOM】
有时我们需要从扁平的数组结构(flat array),根据id,和pid构建出树形数组结构(tree array),这种情形经常出现在嵌套的目录结构,如下图:
或者企业的部门架构,也会出现上面的类似结构。
类似上面的情景,假如我们有以下的数据:
let entries = [{
"id": "12",
"parentId": "0",
"text": "Man",
"level": "1",
"children": null
},
{
"id": "7",
"parentId": "12",
"text": "Other",
"level": "2",
"children": null
},
{
"id": "8",
"parentId": "7",
"text": "Bird",
"level": "3",
"children": null
},
{
"id": "9",
"parentId": "0",
"text": "Woman",
"level": "1",
"children": null
},
{
"id": "11",
"parentId": "9",
"text": "Girl",
"level": "2",
"children": null
}
];
我们期待通过一个算法,构建出下面的结构:
[
{
"id": "12",
"parentId": "0",
"text": "Man",
"level": "1",
"children": [
{
"id": "7",
"parentId": "12",
"text": "Other",
"level": "2",
"children": [
{
"id": "8",
"parentId": "7",
"text": "Bird",
"level": "3",
"children": []
}
]
}
]
},
{
"id": "9",
"parentId": "0",
"text": "Woman",
"level": "1",
"children": [
{
"id": "11",
"parentId": "9",
"text": "Girl",
"level": "2",
"children": []
}
]
}
]
也许我们可以想到,在遍历数组的时候使用递归。没错可以解决问题,但是这种方式并不高效。
最近,在Stack Overflow上看到一个方法,感觉不错,贴出来分享一下:
function list_to_tree(list) {
var map = {
}, node, roots = [], i;
for (i = 0; i < list.length; i += 1) {
map[list[i].id] = i; // initialize the map
list[i].children = []; // initialize the children
}
for (i = 0; i < list.length; i += 1) {
node = list[i];
if (node.parentId !== "0") {
// if you have dangling branches check that map[node.parentId] exists
list[map[node.parentId]].children.push(node);
} else {
roots.push(node);
}
}
return roots;
}
算法的复杂度是Θ(n log(n))。
如果使用递归,那么复杂度是Θ(n^2)。如果数据集比较大,那么执行的时间会很长。
边栏推荐
猜你喜欢
78XX 79XX多路输出电源
LT8918L LVDS转MIPI芯片技术支持资料
与TI的lvds芯片兼容-GM8284DD,GM8285C,GM8913,GM8914,GM8905C,GM8906C,国腾振芯LVDS类芯片,
【面试必看】链表的常见笔试题
Lightly:新一代的C语言IDE
NE5532运放加法器
bluez5.50蓝牙文件传输
Comparative analysis of mobile cloud IoT pre-research and Alibaba Cloud development
MIPI解决方案 ICN6202:MIPI DSI转LVDS转换芯片
Process (present) : custom shell command line interpreter
随机推荐
AD Actual Combat
uniCloud use
字符串哈希
HAL库笔记——通过按键来控制LED(基于正点原子STM32F103ZET6精英板)
2019 - ICCV - 图像修复 Image Inpainting 论文导读《StructureFlow: Image Inpainting via Structure-aware ~~》
哈希表解题方法
剑指Offer 35.复杂链表的复制
同时求最大值与最小值(看似简单却值得思考~)
vector的使用和模拟实现:
剑指Offer 32.Ⅰ从上到下打印二叉树
逆序对数量与归并排序
[Database] Four characteristics of transaction
龙芯2K1000使用nfs挂载文件系统进行使用
【TCS3200 color sensor and Arduino realize color recognition】
【LeetCode】求和
龙讯LT6911系列C/UXC/UXB/GXC/GXB芯片功能区别阐述
408-Binary tree-preorder inorder postorder level traversal
电脑基本知识
剑指Offer 33.二叉搜索树的后序遍历序列
【操作系统】线程安全保护机制