Skip to content Skip to sidebar Skip to footer

Javascript How To Delete Key From Copied Object?

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 du

Solution 1:

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}

Solution 2:

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

Post a Comment for "Javascript How To Delete Key From Copied Object?"