Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively remove object from nested array

i've got array like this. Unlimited number of nesting possible

const myArray = [
  {
   id: 1, 
   children: [
              { 
                id: 3,
                children: []
              }
             ]
  },
  {
   id: 2, children: []
  }
]

Please, help me to remove any object by id and return new array without it.

like image 920
Max Buinevich Avatar asked Mar 04 '26 19:03

Max Buinevich


1 Answers

The recursiveRemove function will recursively remove the elements from the array and return the new list.

The map function creates copy of the items in the array, you can remove the map if you do not need to retain the original array's sanity.

function recursiveRemove ( list, id ) {
    return list.map ( item => { return {...item} }).filter ( item => {
        if ( 'children' in item ) {
            item.children = recursiveRemove ( item.children, id );
        }
        return item.id !== id;
    });
}
const test1 = recursiveRemove ( myArray, 1);
const test2 = recursiveRemove ( myArray, 2);
const test3 = recursiveRemove ( myArray, 3);
like image 81
shreyas888 Avatar answered Mar 06 '26 08:03

shreyas888



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!