Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript How to delete key from copied object? [duplicate]

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?

like image 947
Ramesh Murugesan Avatar asked Nov 25 '15 14:11

Ramesh Murugesan


People also ask

Can we remove a key from object in JavaScript?

Use delete to Remove Object Keys The special JavaScript keyword delete is used to remove object keys (also called object properties). While you might think setting an object key equal to undefined would delete it, since undefined is the value that object keys that have not yet been set have, the key would still exist.

How do you remove a key value pair from an object in TypeScript?

When only a single key is to be removed we can directly use the delete operator specifying the key in an object. Syntax: delete(object_name. key_name); /* or */ delete(object_name[key_name]);

How do you remove an element from an object?

Answer: Use the delete Operator You can use the delete operator to completely remove the properties from the JavaScript object. Deleting is the only way to actually remove a property from an object.


1 Answers

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}
like image 64
Josh Crozier Avatar answered Oct 23 '22 04:10

Josh Crozier