Reputation: 11187
I have a nested array of objects. Something like:
[
{
item: 'x',
data: [
item: 'y',
data: [
item: 'z',
data: [...]
]
],
...
}
]
I know the item I want to remove is located at position [1, 3, 1, 4]
. Is there a faster way to remove that item in the array?
Upvotes: 0
Views: 25
Reputation: 23515
Here is an example of how I would do it. I'm retrieving a pointer to the very array to mutate, then I mutate it.
What this code doesn't do is :
What does this code do :
const arr = [{
item: 'x',
data: [{
item: 'y',
data: [{
item: 'z',
data: [],
}],
},
{
item: 'y2',
data: [{
item: 'z',
data: [{
item: 'a',
data: [],
}, {
item: 'b',
data: [],
}, {
item: 'toRemove',
data: [],
}],
}],
}, {
item: 'y3',
data: [{
item: 'z',
data: [],
}],
},
],
}];
// /!\ Mutate the given object
function removeAtPos(obj, pos) {
// Because we look for a pointer, we dont go all in
// or we would mutate a copy of the data and not the given object data
const allExceptLast = pos.slice(0, pos.length - 1);
// ternary is here to handle the case if we have the first item or not
// First item doesn't start with 'data'
const ptr = allExceptLast.reduce((tmp, x) => tmp.data ?
tmp.data[x] :
tmp[x], obj);
// Finally remove the wanted part of the array
(ptr.data || ptr).splice(pos[pos.length - 1], 1);
}
removeAtPos(arr, [0, 1, 0, 2]);
console.log(arr);
Upvotes: 2