Search code examples
javascriptjavascript-objects

JS: how to use Object.assign to duplicate properties into an array of objects?


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:

  1. Why do I end up with two instances of the object with num = 2?
  2. How can I perform this operation so that the final result is as below?

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


Solution

  • 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.