user841760 user841760 - 1 month ago 8
JSON Question

Javascript, finding object's parents in a JSON

I've got a Json file like this one:

{
"id": 1,
"name": "node",
"nodes": [
{
"id": 2,
"name": "node",
"nodes": [
{
"id": 3,
"name": "node",
"nodes": []
}
]
},


I'd like to have a function where I pass object's "id" and I can get a list of all parent node "id" properties. I guess I'm asking about a recursive function that works one way to get to the desired "id" and then works back up the tree and pushes all the "id" values for every parent (how, I don't know).
Is this possible in JavaScript / Lodash?

Answer Source

you can do so in the following way

let obj = {
    "id": 1,
    "name": "node",
    "nodes": [
      {
        "id": 2,
        "name": "node",
        "nodes": [
          {
            "id": 3,
            "name": "node",
            "nodes": []
          }
        ]
      }
   ]
}
//console.log(obj);

function find(obj, id){
    if(obj.id == id){
        return [id];
    }
    let result = [];
    for(element of obj.nodes){
        //console.log('p', obj.id, 'c', element);
        result = result.concat(find(element, id));
    }
    //console.log(result);
    if(result.length > 0){
        result.push(obj.id);
    }
    return result;
}

console.log(find(obj, 3));