TheWandererr
TheWandererr

Reputation: 514

Remove Object from Array of objects with Parent Child structure

Hey i am creating a Angular Application using PrimeNg UI Framework, and found a problem i cannot solve.

Lets say i have an Array of Objects where there Objects have following structure (Fyi this is the TreeNode of PrimeNg, its the Tree Component under Data).

This is how a singel Node looks like:

{
    label?: string;
    expandedIcon?: any;
    collapsedIcon?: any;
    children?: TreeNode[];
    parent?: TreeNode;
    id?: number;
}

As you can see there is a Parent Child Relation going on.

My Array looks something like this:

    [
      {     Id: 1,
            label: "Books",
            expandedIcon: "fa fa-folder-open",
            collapsedIcon: "fa fa-folder",
            children: [
                       {
                       Id: 2,
                       label: "Horror",
                       expandedIcon: "fa fa-folder-open",
                       collapsedIcon: "fa fa-folder",
                       children: [{
                                  Id: 3,
                                  label: "Stephen King",
                                  expandedIcon: "fa fa-folder-open",
                                  collapsedIcon: "fa fa-folder",
                                  children: null,
                                  parent: undefiend
                                 }],
                        parent: {label: "Books", expandedIcon: "fa fa-folder-open"...}
                       }
                      ];
            parent: undefined;
      },
      {...}
    ]

Now comes my problem: In my application a user can select one of those objects, parent or child (It looks like a Windows Explorer Structure). And if selected i want to delete this object.

My question is how do i find this selected Object in my Array?

Lets say the selected Node is the following.

{
 label: "Stephen King",
 expandedIcon: "fa fa-folder-open",
 collapsedIcon: "fa fa-folder",
 children: null,
 parent: undefiend
}

How can i find this Object in my Array and remove it? Filter can be label or Id.

Upvotes: 0

Views: 1525

Answers (1)

Ranjeet Avghad
Ranjeet Avghad

Reputation: 387

You can do this using recursive function

    function removeSelectedNode(){
      p.forEach((parent)=>{
        deleteFromTree(parent, p)
        })
    }

    function deleteFromTree(obj, parent){
     console.log("rechived", obj)
      if(obj.Id==selectedNode.Id){
      console.log("found", obj)
        var index = parent.findIndex((o)=> o.Id == obj.Id)
        parent.splice(index,1);
        return;
      }
      if(obj.children && obj.children.length>0){
        obj.children.forEach((child)=>{
           deleteFromTree(child, obj.children);    
        })         
      }
    }

where in function replace p with your actual array and set selectedNode somewhere i have tried running this.

Upvotes: 1

Related Questions