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?
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.
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]);
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With