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:
{}
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)
.
assign() pattern in Node 8.
Object.assign() This is another way in assigning Array or Objects to another variable. This method normally creates another reference for the copy of the original one.
There are 3 popular methods which can be used to insert or add an object to an array. The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this method.
Spread in object literals Note that Object.assign() can be used to mutate an object, whereas spread syntax can't. In addition, Object.assign() triggers setters on the target object, whereas spread syntax does not.
You are looking for
var obj = Object.assign({}, ...array)
that creates a new object instead of mutating array[0]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With