简体   繁体   English

从json对象中的特定点开始遍历并找到所有父对象

[英]traverse from a specific point in json object and up to find all parents

I got a json object like this 我有一个像这样的json对象

{
  "id": 1,
  "name": "A",
  "nodes": [
    {
      "id": 2,
      "name": "B",
      "nodes": [
        {
          "id": 3,
          "name": "C",
          "nodes": []
        }
      ]
    }
  ]
}

If I have as input the id of the object, lets take id: 3, how would I scan the whole three find the object with specific id and then scan upwards to the last parent. 如果我输入了该对象的ID,则取ID:3,如何扫描整个三个对象,找到具有特定ID的对象,然后向上扫描到最后一个父对象。

So after the scan is done I know that C has parent B and B has parent A, so I can then print that like ABC 因此,扫描完成后,我知道C具有父B,而B具有父A,因此我可以像ABC一样打印

all based on me knowing the id of object I want to find parents of. 一切都基于我知道我想找到其父母的对象的ID。

The above object can be of any lenght and can have many nodes and levels. 上面的对象可以是任何长度,并且可以具有许多节点和级别。 So anyone has any idea how to traverse up the levels to top level if starting at specific level? 因此,如果有人从特定级别开始,谁知道如何将级别提升到顶级?

edit: 编辑:

when I try to parse this 当我尝试解析这个

let data = [
  {
    "id": 1,
    "name": "name",
    "testing": "something",
    "nodes": [
      {
        "id": 11,
        "name": "name",
        "testing": "something",
        "nodes": []
      }
    ]
  },
  {
    "id": 2,
    "name": "name",
    "testing": "something",
    "nodes": []
  }
]

to json object by doing JSON.parse(data) I get an error 通过做JSON.parse(data)到json对象我得到一个错误

SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)

Also tried this 还尝试了这个

      let jsonObject = JSON.stringify($scope.data);
      jsonObject = JSON.parse(jsonObject);
      createTree(jsonObject, null, nodeData.id)

and get different error: 并得到不同的错误:

TypeError: obj.nodes is not iterable

Do a basic DFS scan, add parent property along the way, and climb up when node found. 进行基本的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM