TDo
TDo

Reputation: 744

Partially copy element from 1 object to another in Javascript

I have 2 objects (object2 has all the keys of object1 plus some additional keys)

object1 = {a:1, b:2}
object2 = {a:0, b:1, c:2}

I would like to update object2's values using object1's values. After the update, object2 will be like this

object2 = {a:1, b:2, c:2}

The value for key c is unchanged. Is there any way to do this in a compact way without looping through all key-value pairs in object1

Upvotes: 1

Views: 60

Answers (4)

aleEspinosaM
aleEspinosaM

Reputation: 444

you can do it with in the spread

const object1 = {a:1, b:2}
const object2 = {a:0, b:1, c:2}
console.log({...obj2, ...obj1}) // output {a: 1, b: 2, c: 2}
//if you are using let you can do the following

object2 = {...obj2, ...obj1}

Upvotes: 0

Karishnu Poddar
Karishnu Poddar

Reputation: 313

If you are fine with using an third party package, you could use the assign method in lodash:

var _ = require('lodash');

object2 = _.assign(object2, object1);

Upvotes: 1

Unmitigated
Unmitigated

Reputation: 89214

You can use Object.assign. However, it will overwrite previous properties in earlier objects, so you need to pass obj2 to it before obj1.

const object1 = {a:1, b:2}, object2 = {a:0, b:1, c:2};
const res = Object.assign({}, object2, object1);
console.log(res);

Upvotes: 2

Namysh
Namysh

Reputation: 4627

You can do something like my example below, it doesn't iterate trought object1 keys

const object1 = {a:1, b:2}
const object2 = {a:0, b:1, c:2}

for(const prop in object2){
  object2[prop] = object1[prop] || object2[prop];
}

console.log(object2)

Upvotes: 0

Related Questions