0

In the example given below, how to correctly pass the value of the iterator?

const result = [];
const a = [1, 2, 3];
const b = {
  x: {
    y: null
  }
};
a.forEach(i => {
  const temp = Object.assign({}, b);
  temp.x.y = i;
  console.log('i : ', temp.x.y);
  result.push(temp);
});
console.log({result});

Output-- >
i: 1
i: 2
i: 3

{
  result: [{
      x: {
        y: 3
      }
    },
    {
      x: {
        y: 3
      }
    },
    {
      x: {
        y: 3
      }
    }
  ]
}

I've experienced similar behaviour in other iteration methods as well, like for loop & map.

How to correctly copy the value of the variable i instead of its reference and pass it on?

Dev
  • 1
  • 1
  • 1
    "I thought that for primitive types, values get assigned instead of reference." — The object you are mutating (i.e. the value of the `x` property) is not a primative. – Quentin Oct 20 '22 at 13:38

0 Answers0