10

I have query object

var q = {
    age: 10, 
    'profile.contry': 'india'
};

Now I duplicate the q variable and remove key from a duplicate variable.

var duplicateQ = q;
delete duplicateQ['profile.contry']; // I have removed 'profile.country' from duplicateQ.

console.log(q); //Object { age: 10 }
console.log(duplicateQ); //Object { age: 10 }

Why are both the variables affected? How can I remove the property from only one of them?

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Ramesh Murugesan
  • 4,727
  • 7
  • 42
  • 67

2 Answers2

11

It's because q and duplicateQ refer to the same object. Thus, when you delete a property on one object, it effects both (since they both point to the same object).

You need to copy/clone the object.

In ES6, you can use the .assign() method:

var q = {age:10, 'profile.contry': 'india'};
var duplicateQ = Object.assign({}, q);
delete duplicateQ['profile.contry'];

Output:

console.log(q);
// {age: 10, profile.contry: "india"}

console.log(duplicateQ);
// Object {age: 10}
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
7

You aren't duplicating q, instead, you're copying a reference to different variable.

Both q and duplicateQ point to the same object, the same location in your computer's memory.

In order to make this work, you're going to have to clone the object, then you can delete (/ modify) individual properties on the separate variables.

A quick-and-dirty example:

var a = { a: 1, b: 2 },
    b = JSON.parse(JSON.stringify(a));

delete b.a;

document.body.textContent = JSON.stringify(a) + ' ' + JSON.stringify(b);
Community
  • 1
  • 1
Cerbrus
  • 70,800
  • 18
  • 132
  • 147