Reputation: 1846
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()
)
Upvotes: 2
Views: 62
Reputation: 6130
You can build your output by iterating on the keys of object1
and using the values of object2
when they exist.
var object1 = {"prop1":"a", "prop2": "b", "prop3":"c"};
var object2 = {"prop2":"d", "prop4": "e", "prop5":"f"};
var output = {};
Object.keys(object1).forEach(function(k) {
output[k] = (object2[k] === undefined ? object1 : object2)[k];
});
console.log(output);
Upvotes: 2
Reputation: 2526
One way to do it would be:
const object1 = {"prop1":"a", "prop2": "b", "prop3":"c"};
const object2 = {"prop2":"d", "prop4": "e", "prop5":"f"};
for (const key in object1) {
if (object1.hasOwnProperty(key) && object2.hasOwnProperty(key)) {
object1[key] = object2[key];
}
}
console.log(object1);
Upvotes: 1
Reputation: 19857
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))
Upvotes: 2