How to add properties from this object to another object?

前端 未结 3 1316
青春惊慌失措
青春惊慌失措 2021-01-28 14:05

Given

var obj1 = {
  a: \'cat\'
  b: \'dog\'
};
var obj2 = {
  b: \'dragon\'
  c: \'cow\'
};

How can I add properties from obj2 to

3条回答
  •  遇见更好的自我
    2021-01-28 14:20

    Solution:

    obj1 = {...obj2, ...obj1};
    

    This solution only works if you know what the expected values might be, e.g. you know they will all be non-empty strings. This uses object spread syntax. You need to ensure that you include obj1 last. You may need a transpiler such as babel until all the browsers (IE...) catch up.

    let obj1 = {
      a: 'cat',
      b: 'dog'
    };
    let obj2 = {
      b: 'dragon',
      c: 'cow'
    };
    obj1 = {...obj2, ...obj1};
    console.log('obj1:', obj1);
    console.log('obj2:', obj2);

提交回复
热议问题