![](/img/trans.png)
[英]Get all parents ids from first level child up the tree in json data object
[英]traverse from a specific point in json object and up to find all parents
我有一個像這樣的json對象
{
"id": 1,
"name": "A",
"nodes": [
{
"id": 2,
"name": "B",
"nodes": [
{
"id": 3,
"name": "C",
"nodes": []
}
]
}
]
}
如果我輸入了該對象的ID,則取ID:3,如何掃描整個三個對象,找到具有特定ID的對象,然后向上掃描到最后一個父對象。
因此,掃描完成后,我知道C具有父B,而B具有父A,因此我可以像ABC一樣打印
一切都基於我知道我想找到其父母的對象的ID。
上面的對象可以是任何長度,並且可以具有許多節點和級別。 因此,如果有人從特定級別開始,誰知道如何將級別提升到頂級?
編輯:
當我嘗試解析這個
let data = [
{
"id": 1,
"name": "name",
"testing": "something",
"nodes": [
{
"id": 11,
"name": "name",
"testing": "something",
"nodes": []
}
]
},
{
"id": 2,
"name": "name",
"testing": "something",
"nodes": []
}
]
通過做JSON.parse(data)到json對象我得到一個錯誤
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
還嘗試了這個
let jsonObject = JSON.stringify($scope.data);
jsonObject = JSON.parse(jsonObject);
createTree(jsonObject, null, nodeData.id)
並得到不同的錯誤:
TypeError: obj.nodes is not iterable
進行基本的DFS掃描,沿途添加parent
屬性,並在找到節點時向上爬。
let jsonParsed = JSON.parse(` { "id": 1, "name": "A", "nodes": [ { "id": 2, "name": "B", "nodes": [ { "id": 3, "name": "C", "nodes": [] } ] } ] } `) let arr = [] function climbTree(obj) { arr.unshift(obj.name) if (obj.parent) { climbTree(obj.parent) } } function createTree(obj, parent = null, targetId = null) { obj.parent = parent if (targetId === obj.id) { return climbTree(obj) } for (let node of obj.nodes) { createTree(node, obj, targetId) } } createTree(jsonParsed, null, 3) console.log(arr.join('-'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.