1

I'm trying to make a deep copy of objects in Javascript:

let test = {
    myProp: "Hello All"
}

let testCopy1 = Object.create(test);
let testCopy2 = JSON.parse(JSON.stringify(test));

// {}
console.log(testCopy1);

// { myProp: 'Hello All' }
console.log(testCopy2);

Why does Object.create() not copy this object? Or was this not the correct way of making a deep copy and there was another "less hacky" alternative to JSON.parse(JSON.stringify(myObject)) ?

James Marino
  • 668
  • 1
  • 9
  • 25
  • 3
    First argument to `Object.create` is a prototype object, which is not the same as 'template' for an object. – Kuba Wyrostek Nov 08 '16 at 12:05
  • The docs on [Object.assign](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) - it doesn't do deep cloning. And refers to your `parse(stringify)` method – Callum Linington Nov 08 '16 at 12:07
  • 2
    *"Why does Object.create() not copy this object?"* Because that isn't what it's designed to do. It doesn't clone objects. When called with just one argument, it creates a new, empty object that uses the object you give as its prototype. That is not a copy. Note that using JSON for this is not only inefficient, but incorrect; what you get back is not a clone of the object (if it even works; JSON doesn't handle circular structures, leaves out functions, leaves out properties whose value is `undefined`, ...). Doing a proper deep clone is non-trivial; see the linked question and its answers. – T.J. Crowder Nov 08 '16 at 12:07
  • I don't know if I personally see `parse(stringify)` as hacky, I think it is a really clever use to get a proper deep clone, first by getting rid of all references and then creating new ones.. – Callum Linington Nov 08 '16 at 12:11
  • 1
    @CallumLinington I think TJ is using the word "hacky" because it has it's downsides & caveats - like not being able to parse the stringified content if it contains non-primitives for example (`Date` being a common one - out of the box anyway) – CodingIntrigue Nov 08 '16 at 12:22
  • @CodingIntrigue i was actually referring to James OP. But yeah there are caveats – Callum Linington Nov 08 '16 at 12:23

0 Answers0