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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With