1

I'm trying to clone and object, then make changes to the original object and do some tests encase the test fails restore the clone back.

Currently I've tried _.clone (underscore), angular.extend, angular.merge, angular.copy, Object.create, Object.assign, JSON.parse(JSON.stringify(o)), but somehow my changes in the original object gets reflected back into the clone.

Let Me Tink About It
  • 15,156
  • 21
  • 98
  • 207
Ash
  • 564
  • 2
  • 5
  • 23

1 Answers1

1

You can shallow copy an object in vanilla JavaScript using Object.assign.

// Shallow copy an object in vanilla JS
let oldObj = {
  name: 'Joe',
  favColor: 'Green',
}

// Shallow copy oldObj to the newObj using assign
var newObj = Object.assign({}, oldObj);

// Changes made to the new object are not reflected in the new object
newObj.favFood = 'pizza';
console.log(oldObj.favFood); // undefined

To perform a "deep copy", you can use JSON.parse(JSON.stringify(a)).

let oldObj = {
  name: 'Joe',
  favColor: 'Green',
  favPizza: {
    cheese: true,
    pepperoni: false,
  },
};

// Deep copy an object using JSON.parse(JSON.stringify(a))
let newObj = JSON.parse(JSON.stringify(oldObj));

// Changes made to the new object are not reflected in the new object
newObj.favPizza.sausage = true;
console.log(oldObj.favPizza.sausage); //undefined

Reference:

  • I did { originalPizza : Object.assign({}, pizza) }, but when i made changes to pizza toppings it got reflected into original pizza. – Ash Dec 15 '16 at 00:55
  • @ArashKiani - I added an example for performing both a "shallow copy" and a "deep copy." I hope it helps! – Joe Karlsson Dec 15 '16 at 01:27