Home > Software design >  How to instantiate default maps?
How to instantiate default maps?

Time:11-06

I want to instantiate different maps starting with default values such as this

const defaultMap: MapType = {
      val1: 0,
      val2: 0,
};

I would then iterate through an array to set values to these different maps:

const useMaps = () => {

useEffect(() => {

    let map1 = defaultMap;

    let map2 = defaultMap;

    let map3 = defaultMap;

console.log(defaultMap)

[val1, val2].forEach((arrayVal) => {
        map1[arrayVal] = 1
        map2[arrayVal] = 2
        map3[arrayVal] = 3
});

*set some states using map1, map2, map3
})

however from the console.log(defaultMap), the value logged does not return

{
      val1: 0,
      val2: 0,
}; 

Why is the constant map changing, and how do I fix this?

CodePudding user response:

All of your map variables reference the same default map object. You need to actually clone the default map, so you each of your map variables reference their own independent copy of the default map.

For a shallow copy, do:

let map1 = {...defaultMap};

For a deep copy, if required, do:

let map1 = JSON.parse(JSON.stringify(defaultMap));
  • Related