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.

5
  • Maybe you need a deep clone? Commented Dec 15, 2016 at 0:33
  • _.clone does shallow copy of the object, but you need a deep copy. Try _.cloneDeep instead. Commented Dec 15, 2016 at 0:33
  • unfortunately we are not using lodash, i've tried to use angular equivalent but all of them reflect the change Commented Dec 15, 2016 at 0:35
  • var clone = JSON.parse(JSON.stringify(o)) may help? Commented Dec 15, 2016 at 0:39
  • @BenAston didnt :( Commented Dec 15, 2016 at 0:57

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

2 Comments

I did { originalPizza : Object.assign({}, pizza) }, but when i made changes to pizza toppings it got reflected into original pizza.
@ArashKiani - I added an example for performing both a "shallow copy" and a "deep copy." I hope it helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.