I search a lots but what I got is how to merge objects and keeps properties of both. How about keep only the same props only? For example:
const obj1 = {a: 1, b:2, c:3}
const obj2 = {a: 3, b:3, d:5, e:7}
Is there any way to create an obj3 which is {a:3, b:3} (only keep props in both objects)?
One option would be to reduce
by obj2
's entries, assigning them to the accumulator object if the property exists in obj1
:
const obj1 = {a: 1, b:2, c:3}
const obj2 = {a: 3, b:3, d:5, e:7}
console.log(
Object.entries(obj2).reduce((a, [key, val]) => {
if (key in obj1) a[key] = val;
return a;
}, {})
);
Accepted answer is a good way to go but the following might turn out to be more efficient;
var obj1 = {a: 1, b:2, c:3},
obj2 = {a: 3, b:3, d:5, e:7},
res = {};
for (k in obj1) k in obj2 && (res[k] = obj2[k]);
console.log(res);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With