0
    const cache = {};
    //adding key-value pair
    cache.John = {lastName:"foo"}
            
    //assigning John to a new variable
    const John = cache.John;
            
    //changing the cache object
    cache.John.lastName = "bar";
            
    console.log(John); // { lastName: 'bar'}

above code shows that even though an object value is saved to a variable and then changed, the variable value also changes.

For my code I need to use a better structure, like a Map, however, when Map value is changed, the reference stays set to the old value.

    const cache = new Map();
    cache.set("John",{lastName:"foo"});
    
    const John = cache.get("John");
    cache.set("John",{lastName:"bar"});
    console.log(John); // { lastName: 'foo'}

Is there a way to also "update" the reference using Map? are there any other structures I could use that are mutable in JavaScript?

nedas1234
  • 35
  • 3
  • You need to clone it when assigning it to the variable if you don't want a reference to the original. `const John = {...cache.John};` Keep in mind that this only provides a shallow copy, any nested objects will still be references. see: [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) and [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) – pilchard Sep 01 '21 at 11:51
  • @pilchard actually the opposite is what I want. I need the reference to change with the original object. – nedas1234 Sep 01 '21 at 11:57
  • Ah, i see, then it's just that you are calling set with a completely new object in your Map example. Instead, get the object from cache, and then mutate it without calling set again, and all referenced variables will update. – pilchard Sep 01 '21 at 11:59
  • Did you try to make your map not a const? – Thallius Sep 01 '21 at 12:02

2 Answers2

1

The reason your Map example isn't working is that you are setting it with a new object after retrieving the original. Instead, you can simply mutate the object from another referenced instance and you'll see the changes in all references.

For more complex interactions you can look at Proxy

const cache = new Map();
cache.set("John",{lastName:"foo"});
    
const John = cache.get("John");

const temp = cache.get("John");
temp.lastName = 'bar';


console.log(John); // { lastName: 'bar'}
pilchard
  • 12,414
  • 5
  • 11
  • 23
0

Just use ... to clone the content of object, Like:

const cache = {};
//adding key-value pair
cache.John = {lastName:"foo"}
        
//assigning John to a new variable
const John = {...cache.John};
        
//changing the cache object
cache.John.lastName = "bar";
        
console.log(John); // { lastName: 'bar'}
Rateb Habbab
  • 1,739
  • 8
  • 13