
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Compare Objects in JavaScript and Return Common Keys with 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']
Advertisements