I want to mix two objects in JavaScript:
let a = {x: 1, y: 2, z:3};
let b = {x:10, y: 20};
let c = Object.assign(a, b);
This gives the correct value for c
:
Object { x: 10, y: 20, z: 3 }
But now a
has been modified too!
Object { x: 10, y: 20, z: 3 }
Is there a way to assign a
onto b
into a new object?
The first argument to assign is the target . So it's going to get changed. You can simply pass an empty object for your target if you don't want any of the sources to change:
let a = {x: 1, y: 2, z:3}; let b = {x:10, y: 20}; let c = Object.assign({},a, b); console.log(c); console.log(a); // a is unchanged
You could use the spread operator :
let a = {x: 1, y: 2, z: 3}; let b = {x: 10, y: 20}; let c = { ...a, ...b } console.log(c); console.log(a);
Definitively the spread operator . It helps to add a single property, like styling CSS in JS. But be aware that it's currently only in stage 4 of EcmaScript.
const lessStyle = {
color: 'blue',
backgroundColor: 'yellow'
};
const moreStyle = {...lessStyle, color: 'red'};
// lessStyle is not affected
You can use it today in Typescript and JSX though.
let a = {x: 1, y: 2, z:3};
let b = {x:10, y: 20};
let c = Object.assign({},a, b);
You need the {} within the assign method for the first object because if you read the documentation for Object.assign method here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Parameters It states that the first parameter is the target object and the rest are the sources. so right now you are assigning b to a and returning the new a to c. So if your first argument is an empty object this won't happen.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.