Skip to content
Related Articles

Related Articles

Improve Article

How to compare two objects to determine the first object contains equivalent property values to the second object in JavaScript ?

  • Last Updated : 23 Apr, 2021

Given two objects obj1 and obj2 and the task is to check the 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




<script>
  
    // 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))
</script>

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




<script>
  
    // 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))
</script>

Output:

true



My Personal Notes arrow_drop_up
Recommended Articles
Page :