javascriptbabeljsecmascript-next

Alternative of Object.assign(...array)


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:

var array=[{interf:'IPerson',name:'Someone'},{clss:'Person',name:'Ahmed'},{student:true}];
console.log(
    Object.assign(...array) // Object.assign(array[0],array[1],array[2])
)

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:

?

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


Solution

  • You are looking for

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

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