What is the most optimal way to delete an object within a array
group of objects.
{
levels: [
{
name: 1,
elements: [
{id: 1},
{id: 2},
{id: 3}
]
}, ...more objects
]
}
I want to delete the element with id 2, however it is inside an array
object, which would be the most optimal way to delete information, without altering the other levels 2, 3, 4, 5
the efficiency depends on many factors, I propose you to use a function to which you pass the object, the level and the index that you want to eliminate and it returns the complete object without that index:
The function, which is very simple, uses a
findIndex
because the objects inside the arraylevels
do not have to be in order, that is, you can havelevels[0]
:and we use
indiceAEliminar -1
because arrays have a base0
. here we should also use afindIndex
, for the same reason as before.Now, if you knew exactly that the elements were inserted in the correct order inside levels and inside elements, the function could be changed by replacing them
findIndex
with the parameter that we passed to it, as follows:I hope this helps.
Whichever way it is implemented, 2 pieces of information are needed, the id to be removed and the element in which the id to be removed is located. The latter could be an index, in which case one of the answers here could be useful :
obj.levels[indice_a_eliminar].elements.splice(1, 1);
, if the reference is something else, for example the attributename
, you can do:The same can be done with other properties, but we will always need a reference.
You can use a filter. If you want to remove the object with id == 2, something like:
Where fElements would contain only the objects with an id different from 2. I think that's decent enough
The splice() method is useful for removing elements from an array.
You just have to pass as an argument the index of the array element to delete, followed by the number 1.
As you can see in this example that is based on your code, the result is the same object whose array is already without the element that we just removed and that had index 1.