Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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']
How It Works
The function uses Object.keys() to get all keys from the first object, then filters them using the filter() method. For each key, it checks two conditions:
-
obj1[key] === obj2[key]- Values must be identical -
obj2.hasOwnProperty(key)- Key must exist in both objects
Alternative Approach Using Object.entries()
const obj1 = { name: "John", age: 25, city: "NYC" };
const obj2 = { name: "Jane", age: 25, city: "NYC", country: "USA" };
const compareObjectsEntries = (obj1, obj2) => {
return Object.entries(obj1)
.filter(([key, value]) => obj2[key] === value)
.map(([key]) => key);
};
console.log(compareObjectsEntries(obj1, obj2));
['age', 'city']
Handling Edge Cases
const compareObjectsSafe = (obj1 = {}, obj2 = {}) => {
if (!obj1 || !obj2 || typeof obj1 !== 'object' || typeof obj2 !== 'object') {
return [];
}
return Object.keys(obj1).filter(key =>
obj2.hasOwnProperty(key) && obj1[key] === obj2[key]
);
};
// Test with null/undefined
console.log(compareObjectsSafe(null, {})); // []
console.log(compareObjectsSafe({a: 1}, null)); // []
console.log(compareObjectsSafe({a: 1}, {a: 1})); // ['a']
[] [] ['a']
Conclusion
Comparing objects for common keys with identical values can be achieved using Object.keys() with filter(). Always validate inputs to handle edge cases like null or undefined objects.
Advertisements
