balumba
balumba

Reputation: 21

Javascript Object delete - deletes another object

I have two Objects:

  var parameters = [{
    id: 1,
    name: "test1"
  }, {
    id: 2,
    name: "test2"
  }];


  var person = {
    name: "Harry",
    parameters: [{
      id: 1
    }, {
      id: 2
    }]
  };

I set person.parameters with the other object:

person.parameters = parameters;

Now I want to delete something from person.parameters:

delete person.parameters[0].id;

Why is parameter[0].id not longer accessible?

console.log(parameters[0].id);

Result:

undefined

Upvotes: 1

Views: 42

Answers (3)

UtkarshPramodGupta
UtkarshPramodGupta

Reputation: 8152

Objects and Arrays are passed by reference.

In Javascript and in almost every programming language, objects and arrays are passed by reference. That means when you set them to a new variable, you don't actually create a copy of it that gets set to the new variable. Instead, it's the same exact array/object in memory that the new variable gets the reference of. Whereas, when you set a variable to a primitive value like a number or a string you actually get a copy of it. So, when you modify an array/object every variable that the object has been referenced within your code would get updated with its new value.

Upvotes: 0

amrender singh
amrender singh

Reputation: 8239

When you do :

person.parameters = parameters;

You just pass reference of the array parameters to person.parameter. So both parameter and person.parameter points to the same reference. Therefore changes made in any one of them will reflect in other.

Basically you have something in the memory as:

a:ref12344−−−+
             |
             |
             |    +−−−−−−−−−−−−−+                 
             +−−−>|  Array      |                 
             |    +−−−−−−−−−−−−−+                 
             |    | obj 1       |         
             |    | obj 2       |
b :ref12345−−+    |             |       
                  |             |
                  +−−−−−−−−−−−−−+

Simply deep copy your array, to make separate references:

person.parameters = parameters.map(a => ({...a}));

Upvotes: 1

Tyrone Wilson
Tyrone Wilson

Reputation: 4618

Because you assigned it to the same object in memory. If you don't want to manipulate the same object you should copy parameters when assigning it to person.

Upvotes: 0

Related Questions