Reputation: 2151
So I just discovered today that doing this:
a = { b: { c: 1, d: 2 }, d: {} }
sub = a.b
// sub is { c: 1, d: 2 }
sub
is now actually the object stored in a, not a clone.
Now if I do this:
sub.c = "x"
// a is now: { b: { c: 'x', d: 2 }, d: {} } // nice
The same thing applies to arrays.
So I have this array:
arr = [{a: 1, b: 2}, {c: 3, d: 4}]
sub = arr[1]
I'd like to remove sub
from array so that arr
becomes: [{a: 1, b: 2}]
but if I do sub = null
I simply assign a new value to sub
. Same thing for delete
.
delete sub // will unset the sub variable, not the object that it references.
So the question is: how do I remove {c: 3, d: 4}
from the array by using sub
Even though it works, I can't use delete arr[1]
because I don't know the index. I'm storing the object using the min
function of lodash
Upvotes: 4
Views: 71
Reputation: 193261
To delete element from array, be it primitive value or object, you still use splice
. To find element index you would use indexOf
. It possible because:
indexOf compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).
So combined together
arr.splice(arr.indexOf(sub), 1);
Take a look at this demo:
var arr = [{a: 1, b: 2}, {c: 3, d: 4}]
var sub = arr[1];
alert('Before: ' + JSON.stringify(arr));
arr.splice(arr.indexOf(sub), 1);
alert('After: ' + JSON.stringify(arr));
Upvotes: 3
Reputation: 943569
So the question is: how do I remove
{c: 3, d: 4}
from the array by using sub
There is no way to do that directly.
Relationships in JavaScript are one-way.
sub
is a reference to an object. arr[1]
is a reference to the same object.
There is no direct way to get from the object to sub
or to arr[1]
.
Since you know arr
contains a reference to the object, you can search for a copy of that reference using indexOf
.
var index = arr.indexOf(sub);
You can then use it to remove the element from the array.
arr.splice(index, 1);
Upvotes: 2