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
  • 9,011
  • 4
  • 19
  • 38
trmaphi
  • 871
  • 1
  • 8
  • 15

0 Answers0