将以上数组处理为嵌套结构数组,以one的值为主体
时间: 2024-03-21 14:42:28 浏览: 22
假设给出的数组如下:
```
var arr = [
{ id: 1, name: 'Node 1', one: 1, parent: 0 },
{ id: 2, name: 'Node 2', one: 2, parent: 1 },
{ id: 3, name: 'Node 3', one: 2, parent: 1 },
{ id: 4, name: 'Node 4', one: 3, parent: 3 },
{ id: 5, name: 'Node 5', one: 4, parent: 4 },
{ id: 6, name: 'Node 6', one: 3, parent: 3 },
{ id: 7, name: 'Node 7', one: 1, parent: 0 },
{ id: 8, name: 'Node 8', one: 2, parent: 7 },
{ id: 9, name: 'Node 9', one: 3, parent: 8 },
{ id: 10, name: 'Node 10', one: 4, parent: 9 }
];
```
可以通过以下方式将其处理为以 `one` 值为主体的嵌套结构数组:
```
function buildNested(arr, parentId) {
var nested = [];
var nodes = arr.filter(node => node.parent === parentId);
var ones = Array.from(new Set(nodes.map(node => node.one)));
ones.sort();
for (var i = 0; i < ones.length; i++) {
var one = ones[i];
var filtered = nodes.filter(node => node.one === one);
if (filtered.length > 0) {
var children = buildNested(arr, filtered[0].id);
var node = {
id: filtered[0].id,
name: filtered[0].name,
one: filtered[0].one,
children: children
};
nested.push(node);
}
}
return nested;
}
var nested = buildNested(arr, 0);
console.log(JSON.stringify(nested));
```
这里定义了一个 `buildNested` 函数,参数 `arr` 为原始数组,`parentId` 为当前节点的父节点 ID。首先,将所有父节点 ID 为 `parentId` 的节点筛选出来,然后找出所有不同的 `one` 值,按升序排序,遍历每个 `one` 值,将相同 `one` 值的节点分别加入到 `nodes` 数组中。如果 `nodes` 数组不为空,则递归调用 `buildNested` 函数,将其子节点添加到当前节点的 `children` 属性中。最后返回 `nested` 数组,即为以 `one` 值为主体的嵌套结构数组。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![js](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)