0
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

endtoend6
  • 65
  • 1
  • 11
  • 1
    `copy === actual`, it is not a copy, it holds a reference to the same exact object. You may want to use `Object.assign` – elclanrs Jan 22 '17 at 20:11

2 Answers2

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;
guest271314
  • 1
  • 15
  • 104
  • 177
  • See also [What is the most efficient way to deep clone an object in JavaScript?](http://stackoverflow.com/q/122102/) – guest271314 Jan 22 '17 at 20:39
1

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;
Michał Pietraszko
  • 5,666
  • 3
  • 21
  • 27