Object.assign(...as) Changes Input Parameter
Object.assign(...as) appears to change the input parameter. Example: const as = [{a:1}, {b:2}, {c:3}]; const aObj = Object.assign(...as); I deconstruct an array of object literals
Solution 1:
Object.assign
is not a pure function, it writes over its first argument target
.
Here is its entry on MDN:
Object.assign(target, ...sources)
Parameters
target
The target object — what to apply the sources’ properties to, which is returned after it is modified.
sources
The source object(s) — objects containing the properties you want to apply.
Return value
The target object.
The key phrase is "[the target] is returned after it is modified". To avoid this, pass an empty object literal {}
as first argument:
const aObj = Object.assign({}, ...as);
Post a Comment for "Object.assign(...as) Changes Input Parameter"