Zero Zero - 23 days ago 7
Javascript Question

Merge two objects but only existing properties

I have two objects. And I want to merge the two objects but only the property value who is only present to the first object.

obj1 : {
"name": "",
"age": ""
}

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


The output I want to be is:

obj1 : {
"name": "Leo",
"age": "14"
}


The
company
and
shift
is no need to merge because that 2 property is not present in
obj1
.

The code I've done so far is:
Object.assign({}, obj1, obj2);


But it's not give me the right output. What it gives is:

merge : {
"name": "Leo",
"age": "14",
"company": "aero",
"shift": "night"
}


Could someone help me how to achieve the output like this:

merge : {
"name": "Leo",
"age": "14",
}


Many thanks!

Answer

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), although it doesn't change much in this case:

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

Or a more fluent approach, but revisits the keys 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]);