endtoend6
endtoend6

Reputation: 75

Deleting a property on an object in the right way

var actual = { first: 1, second : 2 }
var copy = actual;

delete copy.first;

When I console log the copy, it doesnt have the first property on it, but when I console log actual, even that object doesnt have the first property.

Can someone please explain what is happening here? And how to avoid this?

Expected:

actual: { first: 1, second : 2 }
Copy: { second: 2 }

P.S: I know that that I can assign second property directly on the copy object without copying, this is just an example. I'm dealing with very large objects. So I have to copy and then delete the properties without affecting the actual object.

Thank you

Upvotes: 0

Views: 41

Answers (2)

Michał Pietraszko
Michał Pietraszko

Reputation: 6229

You didn't make a copy of the object but just copied the reference. If you want to copy an object, consider using ES6 Object.assign (link) or lodash's assign (link).

Object.assign takes objects as arguments. All properties of objects are copied to first object in argument list and reference to the first object is returned.

var actual = { first: 1, second : 2 };
var copy = Object.assign({}, actual);

delete copy.first;

Upvotes: 1

guest271314
guest271314

Reputation: 1

You can use JSON.stringify(), JSON.parse(), or as suggested by @elclanrs, Object.assign()

var actual = { first: 1, second : 2 }
var copy = JSON.parse(JSON.stringify(actual));
delete copy.first;

var actual = { first: 1, second : 2 }
var copy = Object.assign({}, actual);
delete copy.first;

Upvotes: 1

Related Questions