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?