Aymen Kanzari
Aymen Kanzari

Reputation: 2023

typescript - Assign object to array

I want assign an object to an array, but i have this error in assign function

Expected at least 1 arguments, but got 1 or more

var obj1 = [{ abc: 'abc value' }];

var obj2 = { def: 'new def value'};

var obj3 = Object.assign(...obj1 , obj2) ;

Upvotes: 0

Views: 723

Answers (3)

robertgr991
robertgr991

Reputation: 181

You should use array spreading in this case, Object.assign is used to copy all enumerable own properties from one or more source objects to a target object, so it's not useful in this case.

Take note that array spreading will shallow copy the values of obj1 in the new array with obj2 being put as the last element.

var obj3 = [...obj1, obj2];

If you are targeting IE then you can use:

var obj3 = obj1.slice();
obj3.push(obj2);

Note: Array spreading doesn't work on IE.

From MDN on Object.assign:

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.

Object.assign

Array spread syntax

Upvotes: 0

Andrew Nolan
Andrew Nolan

Reputation: 2107

Depending on what you are trying to do, your method could result in unexpected copying.

const obj1 = [{ abc: 'abc value' }, { abc: 'abc value at index 2' }];
const obj3 = Object.assign(...obj1 , obj2);

will result the last item in the array to override any previous values set where there are matching keys.

{ abc: 'abc value at index 2', def: 'new def value' }

if you are looking to copy something to all objects in the array, you want to use .map() over the array of objects.

const obj1 = [{ abc: 'abc value' }, { abc: 'abc value at index 2' }];
const obj3 = obj1.map(obj => Object.assign(obj, obj2));

Upvotes: 0

Sahil Paudel
Sahil Paudel

Reputation: 598

You need to use Object.assign chaining as below

var obj1 = [{ abc: 'abc value' }];
var obj2 = { def: 'new def value' };
var obj3 = Object.assign(Object.assign({}, ...obj1), obj2 );

Upvotes: 1

Related Questions