Given
var obj1 = {
a: \'cat\'
b: \'dog\'
};
var obj2 = {
b: \'dragon\'
c: \'cow\'
};
How can I add properties from obj2
to
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]
}
}