How to add properties from this object to another object?

前端 未结 3 1266
青春惊慌失措
青春惊慌失措 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:15

    Just check if it exists first and if it doesn't add it!

    for (key in obj2) {
        if (!obj1[key]) obj1[key] = obj2[key]
    }
    

    As RobG pointed out in the comments, this won't work if your values are falsey (0, false, undefined, null, '', etc.) and it will skip past them. If you are always using strings, like in your example it will be ok, but you might as well be safe and comprehensive:

    for (key in obj2) {
        if (!(obj1.hasOwnProperty(key))) {
            obj1[key] = obj2[key]
        }
    }
    

提交回复
热议问题