gpt4 book ai didi

javascript - 如何从 json 字符串中递归获取父 ID

转载 作者:行者123 更新时间:2023-11-28 16:48:01 27 4
gpt4 key购买 nike

{
"id": "1",
"name": "root",
"children": [
{
"id": "1.1",
"name": "Child 1",
"children": [
{
"id": "1.1.1",
"name": "Child 1-1",
"children": [
{
"id": "1-1-1",
"name": "Child 1-1-1",
"children": [

]
}
]
},
{
"id": "1.1.2",
"name": "Child 1-2",
"children": [

]
},
{
"id": "1.1.3",
"name": "Child 1-3",
"children": [

]
}
]
},
{
"id": "1.2",
"name": "Child 2",
"children": [
{
"id": "1.2.1",
"name": "Child 2-2",
"children": [

]
}
]
}
]
}

这是作为响应的 JSON 字符串。必须递归地获取父元素的所有父元素 id。

例如,输入是1.2.1,则返回[1.2] 输入是 1.1.3 然后返回 [1.1, 1]

我怎样才能实现这个目标?

最佳答案

只是使用 dfs 的简单递归

const data = JSON.parse('{"id":"1","name":"root","children":[{"id":"1.1","name":"Child 1","children":[{"id":"1.1.1","name":"Child 1-1","children":[{"id":"1-1-1","name":"Child 1-1-1","children":[]}]},{"id":"1.1.2","name":"Child 1-2","children":[]},{"id":"1.1.3","name":"Child 1-3","children":[]}]},{"id":"1.2","name":"Child 2","children":[{"id":"1.2.1","name":"Child 2-2","children":[]}]}]}')

function dfs (target, node) {
if (node.id === target) { return node.id }
if (!node.children) { return false } // we could even skip that line since in your data you seem to have an empty array
const has = node.children.find(c => dfs(target, c))
return has && [node.id].concat(has.id)
}
console.log(dfs('1.2.1', data))
console.log(dfs('1.1.3', data))

关于javascript - 如何从 json 字符串中递归获取父 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60295173/

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