Reputation: 2509
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.
Upvotes: 4
Views: 2419
Reputation: 620
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);
Upvotes: 7