Object.assign method
The Object.assign method copies
the properties and values of an original
object, while returning a new object. In
the first parameter of the method, we set
the target object to which we are copying,
and in the second, we specify the objects
to be copied.
Syntax
Object.assign(target, objects);
Example
Let's get a new object from the original:
let obj = {'a': 1, 'b': 2, 'c': 3};
let newObj = Object.assign({}, obj);
console.log(newObj);
The code execution result:
{a: 1, b: 2, c: 3}
Example
And now we get a new object from several original ones, listing them in the parameter separated by commas:
let obj1 = {'a': 1, 'b': 2};
let obj2 = {'c': 3, 'd': 4};
let newObj = Object.assign({}, obj1, obj2);
console.log(newObj);
After executing the code, we will see that the two original objects have merged into one new object:
{a: 1, b: 2, c: 3, d: 4}
Example
Also, the Object.assign method can
be used to get a new array, since an array,
by its type, is also an object. Let's make
a new array by copying elements from
the original one:
let arr = [1, 2, 3, 4];
let newArr = Object.assign([], arr);
console.log(newArr);
The code execution result:
[1, 2, 3, 4]
Example
When using the Object.assign method,
you need to be careful about the syntax. For
example, if you do not add the target object
to the first parameter, but leave only the
copied object, then it will return back:
let obj = {1:'a', 2: 'b', 3: 'c'};
let newObj = Object.assign(obj);
console.log(newObj === obj);
The code execution result:
true
See also
-
the
Object.keysmethod
that returns an array of object properties -
the
Object.valuesmethod
that returns an array of object values