TransWikia.com

Javascript changes value of three objects at once

Stack Overflow Asked by oskarmular on November 12, 2021

This is my code and I am trying to change value of object in packs object. But when I type it, Javascript somehow changes all three different objects, that have nothing in common. And this is the only line that changes packs, rest should stay the same, but it’s all changing with this line. How?

                console.log(packs[usedPack].levels[level].bestBy) //null
                console.log(defaultPack.levels[level].bestBy) //null
                console.log(mainPacks[usedPack].levels[level].bestBy) //null

                packs[usedPack].levels[level].bestBy = nameTyped; //this changes values in three different objects
                //packs[usedPack].levels[level] = nameTyped; //if I type like this, this does change only original object, rest stays the same

                console.log(packs) //nameTyped
                console.log(defaultPack) //nameTyped
                console.log(mainPacks) //nameTyped

Edit: It was indeed problem with referencing. I was using constructor function and this function needed to deep copy complex objects. I was checking values and I used multiple loops to copy all values from objects, but it didn’t work properly. I’ve changed all of this to JSON.parse(JSON.stringify()), and it’s working now. Thanks for help.

One Answer

The issue here seems like you're assigning some object by its reference.

In javascript, if you have two objects and you assign them like

a = b;

Now whenever you will change b, a will also be changed. To avoid this we do deep clone using the spread operator

// this now does not reference to b but clones it
a = {...b}

In your code, you might be assigning some objects like this. a=b

Maybe you're assigning packs, defaultPack, and mainPacks using some same object.

Updated

@David pointed out one thing and that is if you are having some complex structure (like objects within object) and then you clone it using spread operator, the inner objects will still reference the same object.

To resolve this, for easiness you can use lodash deepclone function

const clonedeep = require('lodash/clonedeep');
const deepClonedObject = clonedeep(originalObject);

This will deep clone and even if the objects are nested they won't refer to the same object.

Answered by ibrahimijc on November 12, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP