i recently came into a weird(for me) behaviour.
let test = [
{ id: 1, name: 'test1' },
{ id: 2, name: 'test2' },
{ id: 3, name: 'test3' }
]
let test2 = []
test.forEach((elem, index) => {
console.warn(elem, index);
test2.push(elem.name)
elem.arr = test2
})
console.warn(test);
and i want the expected outcome to be like this
[ { id: 1, name: 'test1', arr: [ 'test1'] },
{ id: 2, name: 'test2', arr: [ 'test1', 'test2'] },
{ id: 3, name: 'test3', arr: [ 'test1', 'test2', 'test3' ] }]
but i get this
[ { id: 1, name: 'test1', arr: [ 'test1', 'test2', 'test3'] },
{ id: 2, name: 'test2', arr: [ 'test1', 'test2', 'test3'] },
{ id: 3, name: 'test3', arr: [ 'test1', 'test2', 'test3'] }]
Can someone explain me why this is happening(probably something about references?) and a solution?