JavaScript: Compare two objects to determine if the first one contains equivalent property values to the second one, based on a provided function
JavaScript fundamental (ES6 Syntax): Exercise-179 with Solution
Write a JavaScript program to compare two objects to determine if the first contains equivalent property values to the second one. This is based on a provided function.
- Use Object.keys() to get all the keys of the second object.
- Use Array.prototype.every(), Object.prototype.hasOwnProperty() and the provided function to determine if all keys exist in the first object and have equivalent values.
- If no function is provided, the values will be compared using the equality operator.
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
const matchesWith = (obj, source, fn) =>
Object.keys(source).every(
key =>
obj.hasOwnProperty(key) && fn
? fn(obj[key], source[key], key, obj, source)
: obj[key] == source[key]
);
const isGreeting = val => /^h(?:i|ello)$/.test(val);
console.log(matchesWith(
{ greeting: 'hello' },
{ greeting: 'hi' },
(oV, sV) => isGreeting(oV) && isGreeting(sV)
));
Sample Output:
true
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-179-1 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to create a new object from the combination of two or more objects.
Next: Write a JavaScript program to create a new object from the specified object, where all the keys are in lowercase.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join