Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript/TypeScript - Object assign only available properties

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.

like image 989
MarcoLe Avatar asked Oct 16 '25 10:10

MarcoLe


1 Answers

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);
like image 182
knee pain Avatar answered Oct 19 '25 00:10

knee pain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!