0

I got a json object like this

{
  "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.

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 A-B-C

all based on me knowing the id of object I want to find parents of.

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

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
niko craft
  • 2,893
  • 5
  • 38
  • 67

1 Answers1

3

Do a basic DFS scan, add parent property along the way, and climb up when node found.

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('-'))
Kevin Qian
  • 2,532
  • 1
  • 16
  • 26