2

I want to create a variable unrelated to an existing object but has the same value to the object initially. That means, if I change the new object, it will not affect the old value.

I've tried to use Object.assign({},oldObj), but it doesn't work if I push a value to the array item in the object. Here is my code:

let oldObj = {X:10, Y:[]};
let newObj = Object.assign({},oldObj);
newObj.Y.push(3.29231994);
console.log(oldObj);

Any help will be much appreciated!

hashtabe_0
  • 137
  • 2
  • 3
  • 11

3 Answers3

2

You can use JSON.parse(JSON.stringify()) on that old object to get the new copy of that without any reference:

let oldObj = {X:10, Y:[]};
let newObj = JSON.parse(JSON.stringify(oldObj));
newObj.Y.push(3.29231994);
console.log(oldObj);

If you want shallow copy, use Object.assign({}, a)

For "deep" copy, use JSON.parse(JSON.stringify(a))

Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
  • It is not recommended to use `JSON.parse(JSON.stringify(oldObj))`.What If an object value is a function ? – Mihai Alexandru-Ionut Apr 27 '18 at 08:14
  • @MihaiAlexandru-Ionut if that is so OP needs to mention that. This answer is based on OP's context on what he have asked for providing the code in question – Ankit Agarwal Apr 27 '18 at 08:18
  • It is not recommended to use `JSON.parse(JSON.stringify())`\ method because the biggest problem with using this method to deep-copy an object is the fact the the object must be JSON serializable. – Mihai Alexandru-Ionut Apr 27 '18 at 08:25
1

You can create your own deep copy function.

let oldObj = {X:10, Y:[]};
let newObj = copy(oldObj);
newObj.Y.push(3.29231994);
console.log(oldObj);

function copy(o) {
   var output, v, key;
   output = Array.isArray(o) ? [] : {};
   for (key in o) {
       v = o[key];
       output[key] = (typeof v === "object") ? copy(v) : v;
   }
   return output;
}

It is not recommended to use JSON.parse(JSON.stringify()) method because the biggest problem with using this method to deep-copy an object is the fact the the object must be JSON serializable.

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
  • How often are we in a situation where we want to clone something that Isn't json serializable? All the use cases for cloning an object I've encountered so far involved creating a clone of a data collection. – Shilly Apr 27 '18 at 08:21
  • @Shilly, What if an object value is a function ? – Mihai Alexandru-Ionut Apr 27 '18 at 08:23
  • I haven't had a use case yet in my projects where I had to clone a function, hence I'm asking. If it's a method, we extend the class, if it's a standalone function, we'd just compose or pipe it. So I'm curious about the use cases where cloning a function actually happens. – Shilly Apr 27 '18 at 08:26
  • One example could be when you want to clone a class instance which has methods and properties. – Mihai Alexandru-Ionut Apr 27 '18 at 08:33
  • Why would you do that over creating a new instance with the same inputs? Is cloning it more efficient or something? Cloning a class instance would duplicate all the methods instead of keeping them on the prototype chain. – Shilly Apr 27 '18 at 08:34
  • A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers. For instance, I encountered many problems in javascript with references and i solved them using deep clone – Mihai Alexandru-Ionut Apr 27 '18 at 08:40
  • Its very simple that if the object has only primitive fields, then obviously you will go for shallow copy but if the object has references to other objects, then based on the requiement, shallow copy or deep copy should be chosen. What I mean here is, if the references are not modified anytime, then there is no point in going for deep copy. You can just opt shallow copy. But if the references are modified often, then you need to go for deep copy. Again there is no hard and fast rule, it all depends on the requirement. – Mihai Alexandru-Ionut Apr 27 '18 at 08:43
0

Any variable (or property) referencing a non-primitive is essentially referencing a memory location. So, Arrays, which are just a particular type of Object, are effectively passed by value just like other objects.

If you want to duplicate a non-primitive, you'll have to perform a deep copy - Object.assign only results in a shallow copy.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320