I have this small code snippet:
let data = [1, 2];
let newBody = {};
let newArray = data.reduce((acc, current) => {
newBody.doc = current;
acc.push(newBody);
return acc;
}, []);
The result is:
newArray = [ { doc: 2 }, { doc: 2 } ]
If I'm redeclaring the empty newBody inside the iteration, its working fine. But if I declare it outside its getting the value of the last array element and applying it to all the other elements and I'm not sure why.
If I'm redeclaring the empty newBody inside the iteration, its working fine.<-- that's the answer..map()as opposed to.reduce(). What your code does is equivalent to this: jsfiddle.net/khrismuc/82ezLu3o