Object.assign
A method for merging the object, the source object (source) of all enumerated attribute, copied to the target object (target).
const target = { a: 1 }; const source1 = { b: 2 }; const source2 = { c: 3 }; Object.assign(target, source1, source2); target // {a:1, b:2, c:3}
Object.assign
The first parameter is the target object's method, the source object parameters are behind.
Note that if the source object and the target object has attributes with the same name, or a plurality of source objects of the same name attribute, after the attribute overwrite the previous attribute.
const target = { a: 1, b: 1 }; const source1 = { b: 2, c: 2 }; const source2 = { c: 3 }; Object.assign(target, source1, source2); target // {a:1, b:2, c:3}
important point
(1) shallow copy
Object.assign
The method is practiced shallow copy, rather than a deep copy. That is, the value of a property if the source object is an object, then get a copy of the target object is a reference to the object.
const obj1 = {a: {b: 1}}; const obj2 = Object.assign({}, obj1); obj1.a.b = 2; obj2.a.b // 2
In the above code, the source object obj1
of the a
value of the attribute is an object, Object.assign
the copy obtained is a reference to the object. Any change in this object, will be reflected in the destination object.
(2) replacement of the same name attribute
For this nested object, the event attribute of the same name, Object.assign
the processing method is to replace, rather than adding.
const target = { a: { b: 'c', d: 'e' } } const source = { a: { b: 'hello' } } Object.assign(target, source) // { a: { b: 'hello' } }
The above code, target
object a
attributes are source
object a
properties of the entire replaced, while not get { a: { b: 'hello', d: 'e' } }
results. This is usually not the developers want, need special care.
Some libraries offer Object.assign
customized versions (such as Lodash of the _.defaultsDeep
method) can be obtained with deep copies.
(3) processing array
Object.assign
It can be used to handle an array, but the array will treated as objects.
Object.assign([1, 2, 3], [4, 5]) // [4, 5, 3]
In the above code, Object.assign
the array as an object property named 0,1,2, the source array property 0 4
covered 0 properties of the target array 1
.
Process (4) the value of the function
Object.assign
Copy only values, if you want to copy the value is a function of the value, then evaluated and then copied.
const source = { get foo() { return 1 } }; const target = {}; Object.assign(target, source) // { foo: 1 }
The above code, source
object foo
attribute value is a function that Object.assign
does not copy the values of the function, only later to get the value, copy this value in the past.