Alternative of Object.assign(...array)

Abdennour TOUMI picture Abdennour TOUMI · Aug 17, 2016 · Viewed 72.1k times · Source

Assume we have array of objects.

Calling Object.assign(...array) makes an inheritance among those objects where object with index i override existing properties in object with index i-1

For example:

Now, using Babel with the proposed object spread syntax, we can do this statically :

{...array[0],...array[1],...array[2]} // spread used for each object not for array

How to do that dynamically?

There is overlap of context of "spread syntax". I mean how to use spread syntax for both:

  • For the Array to spread elements.
  • For the output literal object {} to make inheritance

?

I tried {...array} and it returns {0:<array[0]>,1:<array[1]>,2:<array[2]>} which is not the same output as Object.assign(...array).

Answer

Bergi picture Bergi · Aug 17, 2016

You are looking for

var obj = Object.assign({}, ...array)

that creates a new object instead of mutating array[0].