Set the value of an object stored in a variable to null

So, I just discovered today that I am doing this:

a = { b: { c: 1, d: 2 }, d: {} }
sub = a.b
// sub is { c: 1, d: 2 }

sub now actually an 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 goes for arrays.

So I have this array:

arr = [{a: 1, b: 2}, {c: 3, d: 4}]
sub = arr[1]

I would like to remove subfrom the array so that it arrbecomes: [{a: 1, b: 2}]but if I do sub = null, I just assign a new value sub. The same for delete.

delete sub // will unset the sub variable, not the object that it references.

So the question is: how to remove {c: 3, d: 4}from an array usingsub

Despite the fact that it works, I cannot use delete arr[1]it because I do not know the index. I save an object using functionmin lodash

+4
source share
2

, , splice. , indexOf. , :

indexOf searchElement ( , === triple-equals).

arr.splice(arr.indexOf(sub), 1);

:

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));
Hide result
+3

, : {c: 3, d: 4} sub

.

JavaScript .

sub . arr[1] .

sub arr[1].

, arr , indexOf.

var index = arr.indexOf(sub);

.

arr.splice(index, 1);
+2

All Articles