4

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.

2
  • 1
    What is the desired output? Commented Aug 2, 2018 at 7:39
  • 2
    In matter of fact this is what Object.assign will do Commented Aug 2, 2018 at 7:40

1 Answer 1

7

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Oh I messed up, thanks for the clearification. I really thought that the first objs. gets completely overwritten by the second one....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.