Comparing objects in JavaScript and return array of common keys having common values


We are required to write a JavaScript function that takes in two objects. The function should return an array of all those common keys that have common values across both objects.

Example

The code for this will be −

const obj1 = { a: true, b: false, c: "foo" };
const obj2 = { a: false, b: false, c: "foo" };
const compareObjects = (obj1 = {}, obj2 = {}) => {
   const common = Object.keys(obj1).filter(key => {
      if(obj1[key] === obj2[key] && obj2.hasOwnProperty(key)){
         return true;
      };
      return false;
   });
   return common;
};
console.log(compareObjects(obj1, obj2));

Output

And the output in the console will be −

['b', 'c']

Updated on: 20-Nov-2020

532 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements