Home > Enterprise >  How to remove a nested array object in JS?
How to remove a nested array object in JS?

Time:10-18

I am trying to remove the first object from a nested array but somehow I am not able to delete the first object here is my code can you please help?

var arr = [
        {
          demo: [
            {
              label: "NOT - Notification",
              id: "NOT",
              subTree: null,
            },
            { 
              label: "LIM - Limitation", 
              id: "LIM", 
              subTree: null 
            },
          ],
    },
];
      
var ind = arr.findIndex(function (element) {
  return element.demo?.id === "NOT";
});
if (ind !== -1) {
  arr.splice(ind, 1);
}
console.log('this is new', arr);

If you have any better solution then feel free to drop will appreciate your help.

CodePudding user response:

You are accessing the wrong array dimension. Check each subarray in the array:

var arr = [
    {
        demo: [
            {
                label: "NOT - Notification",
                id: "NOT",
                subTree: null,
            },
            { 
                label: "LIM - Limitation", 
                id: "LIM", 
                subTree: null 
            },
        ],
    },
];

for (const item of arr) {
    const index = item.demo.findIndex(subitem => subitem.id === "NOT");
    if (index >= 0) item.demo.splice(index, 1)
}

console.log('this is new', arr);

CodePudding user response:

just add the below snippet:

const newArr = arr.map(data => {
    return { demo : data?.demo.filter(d => d.id != "NOT") }
})
console.log(newArr)

Explanation :
Here, I'm looping through each main array, entering into objects, and then filtering only those with id other than "NOT".

Comment if you stuck with anything in the above code.

CodePudding user response:

As per my understanding after looking in your code, You want to filter out the object which contains id as NOT. If Yes, You can simply achieve that by using Array.filter() method.

Live Demo :

var arr = [
      {
        demo: [
          {
            label: "NOT - Notification",
            id: "NOT",
            subTree: null,
          },
          { 
            label: "LIM - Limitation", 
            id: "LIM", 
            subTree: null 
          },
        ],
  }];
  
const res = arr.map(({ demo }) => demo.filter(({ id }) => id !== 'NOT'));

console.log(res);

  • Related