JavaScript: Compare two objects to determine if the first one contains equivalent property values to the second one
JavaScript fundamental (ES6 Syntax): Exercise-1 with Solution
Write a JavaScript program to compare two objects to determine if the first contains equivalent property values to the second one.
- Use Object.keys() to get all the keys of the second object.
- Use Array.prototype.every(), Object.prototype.hasOwnProperty() and strict comparison to determine if all keys exist in the first object and have the same values.
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
const matches = (obj, source) =>
Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]);
console.log(matches({ age: 25, hair: 'long', beard: true }, { hair: 'long', beard: true })); // true
console.log(matches({ hair: 'long', beard: true }, { age: 25, hair: 'long', beard: true })); // false
console.log(matches({ hair: 'long', beard: true }, { age: 26, hair: 'long', beard: true })); // false
Sample Output:
true false false
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-1-1 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: JavaScript fundamental Exercises
Next: Write a JavaScript program to copy a string to the clipboard.
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