Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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

like image 494
Abdennour TOUMI Avatar asked Aug 16 '16 22:08

Abdennour TOUMI


People also ask

What can I use instead of object assign?

assign() pattern in Node 8.

Can we use object assign for arrays?

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.

How do you assign an object to an array?

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.

Is the spread operator the same as object assign?

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.


1 Answers

You are looking for

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

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

like image 158
Bergi Avatar answered Sep 19 '22 22:09

Bergi