简体   繁体   中英

Remove parent in a nested object hierarchy (tree) retaining children

I am trying to delete an object in a nested object(hierarchical) array with a parent-child relationship. I want to delete an object from this which has the attribute 'required' as false and 'name' is empty or null. When I delete this object, if it is a parent object, I want the children to be attached to the grandparent (parent's parent object). But when I delete it in recursion, the whole element including the child gets deleted. Please help with the recursive approach.

The following is the structure

{
  "name": "abc",
  "nodeId": 1,
  "parentNodeId": null,
  "required": true,
  "children": [
    {
      "name": "",
      "nodeId": 2,
      "parentNodeId": 1,
      "required": false,
      "children": [
        {
          "name": "",
          "nodeId": 3,
          "parentNodeId": 2,
          "required": false,
          "children": [
            {
              "name": "xyz",
              "nodeId": 4,
              "parentNodeId": 3,
              "required": true,
              "children": []
            }
          ]
        },
        {
          "name": "pqr",
          "nodeId": 5,
          "parentNodeId": 2,
          "required": true,
          "children": []
        }
      ]
    }
  ]
}

In the above scenario, the child with name 'xyz' should directly be attached to the nodeId of 1 (abc) as its immediate parents are to be deleted.

I have found this particular solution for deletion based on given condition, but it doesn't retain the child elements.

removeFromTree(root, parent, idx) {
    if (!root.name && root.required === false) {
      if (parent) {
        parent.modelLines.splice(idx, 1);
      }
      else return null;
    }

    if (root.modelLines != null) {
      for (const [i, e] of root.children.entries()) {
        this.removeFromTree(e, root, i);
      }
    }

   return tree;
  };

Please help to address this scenario

You can use the below code snippet to achieve your requirement:

removeFromTree = function(node) {
  var childrenHolder = []
  var accumulator = []

  for(const [i, child] of node.children.entries()) {
    var holder = removeFromTree(child);
    if (child.name || child.required === true) {
      childrenHolder.push(child)
    }
    else {
      accumulator = [...accumulator, ...holder]
    }
  }
  node.children = [...childrenHolder,...accumulator]
  for( var [i, child] of node.children.entries()) {
    child.parentNodeId = node.nodeId
  }
  return node.children
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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