WookieCoder WookieCoder - 4 months ago 14
Javascript Question

Replace shared properties of javascript object

I have two javascript objects, which share several properties.

var object1 = {"prop1":"a", "prop2": "b", "prop3":"c"};
var object2 = {"prop2":"d", "prop4": "e", "prop5":"f"};
//replace shared properties here
//maybe using object.hasOwnProperty???
return object1;
//desired output: {"prop1":"a", "prop2": "d", "prop3":"c"};


I would like to use
object1
as a template to return a set of filters to my user, however, filters may change, and those changes would be saved to object2. I am trying to update properties in object1 with those in object 2, only if they exist in both objects. In this example, for instance, I want to take default values of
prop1
and
prop3
, use object2's value of
prop2
, and ignore
prop4
and
prop5
.
I could easily loop through the properties of object1 and check if they're in object2, but I feel like there must be an easier way to do this (similiar to
union()
or
intersection()
)

Answer

Something like this?

var object1 = {"prop1":"a", "prop2": "b", "prop3":"c"}
var object2 = {"prop2":"d", "prop4": "e", "prop5":"f"}

function mergeCommon (a, b) {
   return Object.keys(a).reduce((obj, prop) => {
     if (prop in b) obj[prop] = b[prop]
     return obj
   }, a)
}

console.log(mergeCommon(object1, object2))