gpt4 book ai didi

javascript - 将树数据转换为具有层次结构路径的平面数据作为数组

转载 作者:行者123 更新时间:2023-12-01 01:36:41 25 4
gpt4 key购买 nike

我有以下数据。我需要创建一个平面数据结构,其层次结构作为数组。如何使用递归函数创建它?

    var tree = [{
"name": "Firm",
"id": 1,
"children": [{
"name": "veniam",
"id": 2
},
{
"name": "officia",
"id": 3
},
{
"name": "ullamco",
"id": 4
},
{
"name": "duis",
"id": 5,
"children": [{
"name": "aliquip",
"id": 6,
"children": [
{
"name": "culpa",
"id": 7
},
{
"name": "qui",
"id": 8
},
{
"name": "cillum",
"id": 9
}
]
}]
},
{
"name": "ullamco",
"id": 10
},
]
}];

我想要的结果应该是这样的。

[{
"name": "Firm",
"id": 1,
"path": [1]
},
{
"name": "veniam",
"id": 2,
"path": [1, 2]
},
{
"name": "officia",
"id": 3,
"path": [1, 3]
},
{
"name": "ullamco",
"id": 4,
"path": [1, 4]
},
{
"name": "duis",
"id": 5,
"path": [1, 5]
},
{
"name": "aliquip",
"id": 6,
"path": [1, 5, 6]
},
...
{
"name": "ullamco",
"id": 10,
"path": [1, 10]
}
]

有人可以帮忙吗?

最佳答案

var tree=[{name:"Firm",id:1,children:[{name:"veniam",id:2},{name:"officia",id:3},{name:"ullamco",id:4},{name:"duis",id:5,children:[{name:"aliquip",id:6,children:[{name:"culpa",id:7},{name:"qui",id:8},{name:"cillum",id:9}]}]},{name:"ullamco",id:10}]}];

function flatten(node, path = [], array = []) {
const { id, name } = node
const newPath = [...path, id]
const children = node.children || []
array.push({ id, name, path: newPath })
children.forEach(child => {
flatten(child, newPath, array)
})
return array
}

console.log(flatten(tree[0]))

关于javascript - 将树数据转换为具有层次结构路径的平面数据作为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52767591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com