5

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

2
  • 1
    Either create your own algorithm or use a library like lodash Commented Aug 23, 2018 at 2:32
  • should it show the matching properties and the values ​​of object 2? Commented Aug 23, 2018 at 3:30

4 Answers 4

6

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;
  }, {})
);

Sign up to request clarification or add additional context in comments.

2 Comments

Not gonna get much better than that
That's nice. Thank you. :D
2

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

Comments

1

You could convert to an array (with the help of Object.entries) to filter – then convert back (with the help of reduce)

Object.entries(obj2)
    .filter(([key]) => (key in obj1))
    .reduce((obj, [key, val]) => ({...obj, [key]: val}), {})

Comments

0

Here's a way that tries to improve efficiency by looping over the object with fewer keys (less iterations):

const obj1 = {a: 1, b:2, c:3}
const obj2 = {a: 3, b:3, d:5, e:7}

// find sm/lg object by key length
let [sm,lg]=[obj1,obj2].sort((a,b)=>(
  Object.keys(a).length-Object.keys(b).length
));

const merged = {}

// make small object outer loop 
for (let key in sm){
  if (key in lg)
    merged[key]=obj2[key] // only store if key in both objects
}

console.log(merged);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.