Reputation: 355
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.
Upvotes: 0
Views: 1320
Reputation: 27212
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);
Upvotes: 1
Reputation: 1117
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.
Upvotes: 1
Reputation: 195
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);
Upvotes: 1