You are passing in the same reference to the array everytime. You are updating that same value too i.e., test[0]
.
So in the end, you have an array with three elements, all 3 pointing to the same object whose id
property you have updated to the final value - test2[2].id
.
You can directly push in an object with the correct id
property. You will not need an extra test array as you are creating your object and pushing them on the go.
let test = [ { id: 1 } ];
let test2 = [
{ id: 1 },
{ id: 2 },
{ id: 3 }
];
let x = []
test2.forEach(i => {
x.push({ id : i.id })
});
console.log(x)