1

Let's say I have class called Person, which have firstName, lastName, and Array of addresses fields.

And in one of my angular components I am getting Person object to do some operation on them. But I would like to create two copies of this obj. To do that I am using Object.assign. But after that when I am manipulating firstName from firstCopyPerson all other objects are changed too.

How can I assign object to new variable without making reference to orginal object, but instead just creating new separate object?

mainPerson: Person;
firstCopyPerson: Person;
secondCopyPerson: Person;

ngOnInit() {
    this.mainPerson = someCache.getPerson(); 
    this.firstCopyPerson: Object.assign({}, this.mainPerson);
    this.secondCopyPerson: Object.assign({}, this.mainPerson);
}
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Suule
  • 2,197
  • 4
  • 16
  • 42
  • 2
    https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript look into this. – Cerceis Jun 08 '21 at 07:14
  • 2
    Does this answer your question? [What is the most efficient way to deep clone an object in JavaScript?](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript) – Cerceis Jun 08 '21 at 07:15

3 Answers3

1

You can add this re-usable function so you can reuse this function everytime

const copyObject = (obj) => {
  let result = {};
  Object.entries(obj).forEach(([key, value]) => {
    result[key] = value;
  });
  return result;
};

// Test the function
const obj1 = {name: 'notebook', price: 100};
objCopy = copyObject(obj1);
console.log(objCopy);

You can also use this way

const obj = {name: 'laptop', price: 100};

// This is the implementation line
let objCopy = {...obj};

console.log(objCopy);
Dhana D.
  • 1,670
  • 3
  • 9
  • 33
0

whenever you use this code you are assigning a new reference to the object and both variables assigning to the same object so when you edit one of them the other will change too. you can solve this by destructing the object for example you can try this :

let personCopy = {...person}
0

Object.assign would only make a shallow copy of the object, that means all attributes are assigned to the same data objects.

You may want to read about deep copies which are the safe way to go.

Fenton already posted a brilliant answer to this, take a look at option 4 in his answer: https://stackoverflow.com/a/28152032/8341158

michael.k
  • 168
  • 9