Sunil
Sunil

Reputation: 11243

Get parent in javascript without modifying object

I have original nested object which contains the huge tree kind of structure. This is is basically JSON string which is converted into JavaScript object.

Structure is like -

original = {
       type :  "table",
       children :[
           {
             type : "cell",
             children : [
                {
                   type : "label",
                   children : []
                }
             ]
           }
           {
             type : "cell",
             children : []
           }
       ]
    }

I have selected item as -

var select = original.children[1].children[0];

What I want is get the parent of selected item.

Here is sample demo - https://stackblitz.com/edit/angular-v5m9ua

Note : I need to trace over the original object to find the parent. I had looked at the other answers but they had mentioned how to design the object structure to get the parent but I don't want to change the original object.

Upvotes: 0

Views: 132

Answers (2)

Nenad Vracar
Nenad Vracar

Reputation: 122027

You could create recursive function with for...in loop and return last parent element that was of object type.

const data = {
  type: "table",
  children: [{
    type: "cell",
    children: [{
      type: "label",
      children: []
    }]
  }, {
    type: "cell",
    children: []
  }]
}
var select = data.children[0].children[0];

function getParent(data, obj, parent = null) {
  let result = null;

  (function loop(data, obj, parent) {
    if (typeof data == 'object' && !Array.isArray(data)) {
      parent = data
    }

    for (let i in data) {
      if (select == data[i]) {
        result = parent;
        break;
      }

      if (typeof data[i] == 'object') {
        loop(data[i], obj, parent)
      }
    }
  })(data, obj, parent)

  return result;
}

let parent = getParent(data, select)
console.log(parent)

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138237

You could search the tree:

 findParent(root, toFind) {
    for(const child of root.children || []) {
      if(child === toFind){
         return root;
      } 
      const result = this.findParent(child, toFind);
      if(result){
        return result;
      } 
    }
}

That can be used as:

  findParent(original, select)

Upvotes: 0

Related Questions