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?

6
  • duplicateQ is a reference to the original q. You need to clone the object. See the answer I marked as duplicate for more information. Commented Nov 25, 2015 at 14:24
  • @RoryMcCrossan: Technically, the OP is asking how to delete a property from a cloned object. While the "Cloning" is the problem, There's gotta be a better duplicate out there... (Not that I've found one yet) Commented Nov 25, 2015 at 14:27
  • 1
    True, although his method of deletion is correct. The problem he has is addressed by the dupe question. Commented Nov 25, 2015 at 14:28
  • 1
    I propose: stackoverflow.com/questions/728360/… (Which I can apply, if you agree) Commented Nov 25, 2015 at 14:29
  • 1
    I agree - that one is more generic. Commented Nov 25, 2015 at 14:30

2 Answers 2

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}
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.