0

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

double-beep
  • 5,031
  • 17
  • 33
  • 41
  • 2
    Can you share a minimal, reproducible example? – Yousaf Apr 04 '21 at 11:09
  • 1
    `Object.assign` assigns just a shallow copy. Thus, any ties/links/references that are nested deeper than just on object hierarchy level are kept. – Peter Seliger Apr 04 '21 at 11:11
  • 1
    We can't help you with code we can't see. :-) Please update your question with a [mcve] demonstrating the problem, ideally a **runnable** one using Stack Snippets (the `[<>]` toolbar button); [here's how to do one](https://meta.stackoverflow.com/questions/358992/). At a guess, it sounds like you're changing the state of an object that is referenced by a property on `words.oldScore`. `Object.assign` just makes a shallow copy. If you want to *also* copy that other object that's referenced, you have to do that separately. – T.J. Crowder Apr 04 '21 at 11:11
  • 2
    If you want to make a copy of the entire tree, see [this question's answers](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript). – T.J. Crowder Apr 04 '21 at 11:12

3 Answers3

2

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

Yousaf
  • 27,861
  • 6
  • 44
  • 69
Ravikumar
  • 2,085
  • 12
  • 17
1

[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));
KooiInc
  • 119,216
  • 31
  • 141
  • 177
0

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));