简体   繁体   English

在JavaScript中获取父级而不修改对象

[英]Get parent in javascript without modifying object

I have original nested object which contains the huge tree kind of structure. 我有original嵌套对象,其中包含巨大的树形结构。 This is is basically JSON string which is converted into JavaScript object. 这基本上是JSON字符串,可以转换为JavaScript对象。

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. 我想要的是获取selected项目的parent项。

Here is sample demo - https://stackblitz.com/edit/angular-v5m9ua 这是示例演示-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. 我查看了其他答案,但是他们提到了如何设计对象结构以获取父对象,但我不想更改原始对象。

You could create recursive function with for...in loop and return last parent element that was of object type. 您可以使用for...in循环创建递归函数,并返回对象类型的最后一个父元素。

 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) 

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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