-1

I am trying to remove the first object from an 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.

Milan Sachani
  • 335
  • 3
  • 8
  • 2
    `element.demo?.id === "NOT"` -> `element.demo?.[0].id === "NOT"` if you have one item in the array or `element.demo?.some(x =>x?.[0].id === "NOT"`)` for multiple. – VLAZ Oct 17 '22 at 13:49
  • Use `some()` to check all the object in the demo array. `element.demo.id` does not take into account that it's an array. – 0stone0 Oct 17 '22 at 13:49
  • element.demo?.some(x =>x?.[0].id === "NOT") with this it throws undefined error – Milan Sachani Oct 17 '22 at 14:03

2 Answers2

0

The demo property in your object refers to an array, so you will need to access the first nested object with an index, e.g. element.demo[0].id.

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

const ind = arr.findIndex(element => element.demo[0].id === "NOT");

if (ind !== -1) {
  arr.splice(ind, 1);
}

console.log('this is new', arr);
Terry
  • 63,248
  • 15
  • 96
  • 118
-3

This should work:

arr = arr.filter(item => demo?.id !== "NOT");

It filters all items where id is not equal to "NOT".

Joost00719
  • 716
  • 1
  • 5
  • 20