How to compare two objects to determine the first object contains equivalent property values to the second object in JavaScript ?
Given two objects obj1 and obj2 and the task are to check that obj1 contains all the property values of obj2 in JavaScript.
Input: obj1: { name: "John", age: 23; degree: "CS" } obj2: {age: 23, degree: "CS"} Output: true Input: obj1: { name: "John", degree: "CS" } obj2: {name: "Max", age: 23, degree: "CS"} Output: false
To solve this problem we follow the following approaches.
Approach 1: It is a naive approach to solve this problem. In this approach, we iterate the obj2 using the for..in loop and at every iteration, we check the current key of both objects are not equal we return false otherwise after completion the loop we return true.
Example:
Javascript
// Define the first object let obj1 = { name: "John" , age: 23, degree: "CS" } // Define the second object let obj2 = { age: 23, degree: "CS" } // Define the function check function check(obj1, obj2) { // Iterate the obj2 using for..in for (key in obj2) { // Check if both objects do // not have the equal values // of same key if (obj1[key] !== obj2[key]) { return false ; } } return true } // Call the function console.log(check(obj1, obj2)) |
Output:
true
Approach 2: In this approach, we create an array of all the keys of obj2 by using the Object.keys() method and then using the Array.every() method we check if all the properties of obj2 are equal to obj1 or not.
Example:
Javascript
// Define the first object let obj1 = { name: "John" , age: 23, degree: "CS" } // Define the Second object let obj2 = { age: 23, degree: "CS" } // Define the function check function check(obj1, obj2) { return Object // Get all the keys in array .keys(obj2) .every(val => obj1.hasOwnProperty(val) && obj1[val] === obj2[val]) } // Call the function console.log(check(obj1, obj2)) |
Output:
true
Please Login to comment...