Merge two objects but only existing properties

Assuming you only want enumerable properties, this is easily done with Object.keys and in (or hasOwnProperty):

Object.keys(obj2).forEach(function(key) {
    if (key in obj1) { // or obj1.hasOwnProperty(key)
        obj1[key] = obj2[key];
    }
});

Example:

var obj1 = {
  "name": "",
  "age": ""
};

var obj2 = {
  "name": "Leo",
  "age": "14",
  "company": "aero",
  "shift": "night"
};

Object.keys(obj2).forEach(function(key) {
  if (key in obj1) { // or obj1.hasOwnProperty(key)
    obj1[key] = obj2[key];
  }
});
console.log(obj1);

Or in ES2015 syntax (since you mentioned Object.assign):

for (const key of Object.keys(obj2)) {
    if (key in obj1) { // or obj1.hasOwnProperty(key)
        obj1[key] = obj2[key];
    }
}

Or a more fluent approach, but revisits the keys that are in obj1 (not that it’s likely to matter:

Object.keys(obj2).filter(key => key in obj1).forEach(key => {
    obj1[key] = obj2[key];
});

Since forEach ignores the return value of its callback, we could even go further in the concise-land:

Object.keys(obj2).filter(key => key in obj1).forEach(key => obj1[key] = obj2[key]);

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)