Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - How to merge to objects but keep only the same properties

Tags:

javascript

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)?

like image 659
Jam Nguyen Avatar asked Aug 23 '18 02:08

Jam Nguyen


2 Answers

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;
  }, {})
);
like image 98
CertainPerformance Avatar answered Oct 12 '22 10:10

CertainPerformance


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);
like image 30
Redu Avatar answered Oct 12 '22 09:10

Redu