I'm trying to duplicate key-value pairs from one object into each distinct object inside an array.
const propsToDuplicate = {
foo: 'foo',
bar: 'bar'
};
const items = [{
num: 1
},
{
num: 2
}
];
const result = items.map(item => {
console.log('item: ', item);
const moar = Object.assign(propsToDuplicate, item);
console.log('item with more stuff: ', moar);
return moar;
});
console.log(result);
Questions:
num
= 2? Desired result:
[ { foo: 'foo', bar: 'bar', num: 1 },
{ foo: 'foo', bar: 'bar', num: 2 } ]
Here is the sandbox:
https://repl.it/@montrealist/array-map-and-object-assign-weirdness
Object.assign(a, b, c)
will assign everything from a
, b
, and c
into the object that is the first parameter to assign()
.
In your case you are using propsToDuplicate
as the first parameter, and this means that that each time assign()
is called, propsToDuplicate
is being mutated.
Change const moar = Object.assign(propsToDuplicate, item);
to const moar = Object.assign({}, propsToDuplicate, item);
and you should be good to go.