LesDentsDeLaMer
LesDentsDeLaMer

Reputation: 69

Changes to object still reflected after object assign

I assign oldScore to newScore.

Later on when I update the newScore object, the changes are reflected to oldScore, can someone assist?

The changes made to newScore should not be reflected to oldScore. newScore and oldScore are two distinct and different objects.

words.newScore = Object.assign( {}, words.oldScore );

Thank you

Upvotes: 0

Views: 535

Answers (3)

KooiInc
KooiInc

Reputation: 122906

[revised 2021/04/05]

If words.oldScore does not contain keys with values being or containing objects themselves, you can also use the spread syntax to copy it (see snippet).

Otherwise you need to device a way to copy/clone words.oldScore. Here is an example for that

const words = {
  oldScore: {score: 43, word: "some foo"},
};

words.newScore = {...words.oldScore};
words.newScore.word = "some bar";
console.log(JSON.stringify(words, null, 2));

Upvotes: 1

LesDentsDeLaMer
LesDentsDeLaMer

Reputation: 69

Thank you all, yes i was trying to update values nested deep into the object. I didn't understand the concept of "shallow copy" now it's clear i'm gonna investigate this. Once again thank you and happy Sunday

EDIT: this is the solution i chose (when speed is not a must this example works fine) var newObject = JSON.parse(JSON.stringify(oldObject));

Upvotes: 0

Ravikumar
Ravikumar

Reputation: 2205

Object.assign will shallow copy, means toplevel object's own properties only. May you are trying to update nested object's values, thus it's updating old instance too. For that you need to Deep Copy instances. For more details refer: MDN - Object.assign(): Warning for Deep Clone

Upvotes: 3

Related Questions