js中的数组转树型结构方式
作者:酥脆角
什么是数组转树型结构
将数组中的元素按照特定规则组织成一个树形结构,专业术语是数组转树。
具体实现方式可能因情况而异,但通常需要考虑以下几个要素:
- 数组中元素的顺序和位置如何影响树的结构;
- 树的节点应包含哪些信息,例如值、子节点等;
- 如何确定每个节点的父节点和子节点的索引或指针;
- 如何处理数组中缺失的节点或空值。
- 在实际应用中,可能还需要考虑对树进行遍历、搜索等操作的效率问题。
应用场景: 比如前端开发中的菜单导航、商品分类等。
实现数组转树型结构的一般思路是
- 遍历数组,将每个元素转换为树节点对象(通常包含 id 和 parentId 等属性)。
- 将所有节点按照 parentId 属性进行分组,形成一个以 parentId 为键、以对应节点数组为值的字典。
- 找到根节点(即没有父节点或其父节点不在数组中的节点),并递归构建整个树形结构。
下面是一个基于 JavaScript 的示例代码实现:
function arrayToTree(list, parentId = null) {
const arr = []
list.forEach(item => {
if (item.pid === parentId) {
// 找到了匹配的节点
// 当前节点的id 和 当前节点的子节点的pid是相等的
const children = transListToTreeData(list, item.id)
// 找到的节点的子节点
item.children = children
arr.push(item)
}
})
return arr
}
// 使用示例
const array = [
{ id: 1, name: 'A', parentId: null },
{ id: 2, name: 'B', parentId: 1 },
{ id: 3, name: 'C', parentId: 1 },
{ id: 4, name: 'D', parentId: 2 },
{ id: 5, name: 'E', parentId: 2 },
{ id: 6, name: 'F', parentId: 3 },
{ id: 7, name: 'G', parentId: null }
];
const tree = arrayToTree(array, null);
console.log(tree);在上述代码中,arrayToTree 函数接收一个数组和可选的 parentId 参数,用于指定父节点的 id 值。
在函数内部,首先判断数组中的 id跟 parentId 是否相等,相等的就将对象添加到此对象的子数组中,在当中定义的 arr 就是筛选出来的数组,再重新调用一下 arrayToTree 函数构建子树,最后返回包含当前节点以及其子树的对象。
示例代码运行结果如下:
[
{
"id": 1,
"name": "A",
"parentId": null,
"children": [
{
"id": 2,
"name": "B",
"parentId": 1,
"children": [
{
"id": 4,
"name": "D",
"parentId": 2,
"children": []
},
{
"id": 5,
"name": "E",
"parentId": 2,
"children": []
}
]
},
{
"id": 3,
"name": "C",
"parentId": 1,
"children": [
{
"id": 6,
"name": "F",
"parentId": 3,
"children": []
}
]
}
]
},
{
"id": 7,
"name": "G",
"parentId": null,
"children": []
}
]注意:
数组转树型结构是封装一个函数来进行对数据的筛选, 将筛选出来的对象添加到父节点的子节点上,并且再调用一下此函数,形成递归,就可以实现数组转树,这样在拿到平铺数据时就可以得到嵌套数据了。
关于扁平数组转树型数组这件事
项目中很难避免扁平转树型或者树型转扁平这件事情,所以我们在查看到数据的时候,可以根据这个数据的规则来定义一个方法。这样在数据规则相同的时候我们就可以调用这个方法。
准备数据
const arr = [
{ id: 1, name: "万科", pid: "" },
{ id: 11, name: "1栋", pid: 1 },
{ id: 111, name: "1单元", pid: 11 },
{ id: 12, name: "2栋", pid: 1 },
{ id: 2, name: "汤臣一品", pid: "" },
];方法一:递归实现扁平数组转换成树型数组
封装一个函数
function tranListToTreeData(list, rootValue) {
const arr = [];
list.forEach((item) => {
if (item.pid === rootValue) {
// 递归调用
const children = tranListToTreeData(list, item.id);
if (children.length) {
item.children = children;
}
arr.push(item);
}
});
return arr;
}调用这个函数将要匹配的规则穿进去并打印出来
tranListToTreeData(arr, "");
console.log(
'[ tranListToTreeData(arr, ""); ] >',tranListToTreeData(arr, "")
);你会发现你得到了一个树型数组。

但是我们定义一个i,看一看这个函数总共运行了多少次
var i = 0;
function tranListToTreeData(list, rootValue) {
const arr = [];
list.forEach((item) => {
if (item.pid === rootValue) {
// 递归调用
const children = tranListToTreeData(list, item.id);
if (children.length) {
item.children = children;
// i++;
}
arr.push(item);
}
i++;
console.log("[ i ] >", i);
});
return arr;
}
tranListToTreeData(arr, "");
console.log(
'[ tranListToTreeData(arr, ""); ] >',
tranListToTreeData(arr, "")
);
打印的结果最终为60次,因为递归是函数嵌套函数,外面每循环一次,里面的函数都要循环一遍。我们现在数据还不多,要是数据多了的话是很耗性能的。下面我们来看一下对象的方法实现这个递归来优化性能。
方法二:利用对象实现扁平数组转换成树型数组
还是那个数据
const arr = [
{ id: 1, name: "万科", pid: "" },
{ id: 11, name: "1栋", pid: 1 },
{ id: 111, name: "1单元", pid: 11 },
{ id: 12, name: "2栋", pid: 1 },
{ id: 2, name: "汤臣一品", pid: "" },
];// 1.得到一个对象
function tranListToTreeData(list, pid) {
var map = {};
list.forEach((item) => {
if (map[item.pid]) {
map[item.pid].push(item);
} else {
map[item.pid] = [item];
}
});
return map;
}
const result = tranListToTreeData(arr, "");
console.log(result);遍历数据的每一项,有pid的话就追加到map中,没有的话就将这条数据赋值给map对象的每一项的pid,最后我们就会得到如下这个对象,你会发现,pid相同的数据在同一个数组中。

利用第一步得到的对象对原数组进行修改
list.forEach((item) => {
if (map[item.pid]) {
item.children = map[item.id];
}
});看图你会发现,刚刚得到的数组中都有子节点了

最后主需要过滤掉不需要的数组就行了
map = list.filter((item) => item.pid == pid);

现在可以测试一下我们这个方法需要循环多少次。
// 把扁平数组转成树型数组
// 1.得到一个对象
var i = 0;
function tranListToTreeData(list, pid) {
var map = {};
list.forEach((item) => {
if (map[item.pid]) {
map[item.pid].push(item);
} else {
map[item.pid] = [item];
}
i++;
});
//2. 利用第一步得到的对象对原数组list进行修改
list.forEach((item) => {
if (map[item.pid]) {
item.children = map[item.id];
// console.log(
// "[JSON.stringify( map[item.id]) ] >",
// JSON.stringify(map[item.id])
// );
}
i++;
});
// 3.过滤
map = list.filter((item) => {
i++;
return item.pid == pid;
});
console.log("[ i ] >", i);
return map;
}
const result = tranListToTreeData(arr, "");
console.log(result);```
最后我们可以看到只执行了15次,这对性能来说,省了四分之三总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
