0

I got a weird problem on using spread operator to clone nested obj.

The constant of a local scope is copy from a const in global scope using spread operator. If I change a value of a property in 1 level deep. The change will appears on the global variables too.

const foo = {
    a: {
        a1: 'a1',
        a2: 'a2',
    },
    b: 'b',
};

(() => {
    const bar1 = { ...foo };
    bar1.a.a1 = 'changed';
})();

console.log(foo);

How could I prevent this behavior?

Fraction
  • 11,668
  • 5
  • 28
  • 48
trmaphi
  • 901
  • 1
  • 9
  • 16

0 Answers0