Following usecase: Lets assume I have an object with following properties:
const objOne = {
car: 'ford',
location: 'Munich',
driver: 'John'
}
and a second Obj that only has some of the first Obj's properties:
const objTwo = {
car: 'BMW',
driver: 'Marta'
}
Is there a way to assign the properties from the second obj to the first obj without loosing the properties from the first obj. In this case location: 'Munich'
. I know for a fact there is a method like Object.assign
but this method completely copies the targeted obj, which I obviously don't want to.
This is exactly the behaviour of Object.assign
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
const objOne = {
car: 'ford',
location: 'Munich',
driver: 'John'
}
const objTwo = {
car: 'BMW',
driver: 'Marta'
}
console.log(objOne);
console.log(objTwo);
Object.assign(objOne, objTwo);
console.log('--assign--');
console.log(objOne);
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