
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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']
- Related Questions & Answers
- Add property to common items in array and array of objects - JavaScript?
- Add values of matching keys in array of objects - JavaScript
- Python - Combine two dictionary adding values for common keys
- Return the greatest common divisor and lowest common multiple in Numpy
- Split keys and values into separate objects - JavaScript
- How to get the most common values in array: JavaScript ?
- Function to check two strings and return common words in JavaScript
- Smallest Common Multiple of an array of numbers in JavaScript
- How to filter out common array in array of arrays in JavaScript
- Grouping array nested value while comparing 2 objects - JavaScript
- Maps in JavaScript takes keys and values array and maps the values to the corresponding keys
- Calculating least common of a range JavaScript
- PHP Comparing Objects
- Find and return array positions of multiple values JavaScript
- Finding maximum length of common subarray in JavaScript
Advertisements