Search code examples
javascriptlodash

compare two objects and return true if part of the object key value pair exists


I need to compare two objects and return true or false based on the below logic.

const expectedValue = {
            city: "San Jose",
            state: "california",
            zip: "95234"
         }

const actualValue = {
            address: "5543322 Adam St",
            city: "San Jose",
            state: "california",
            zip: "95234",
            country: "USA"
}

When the above objects are compared, it should return "TRUE", as expectedValue's key value pair exists in the actualValue. I couldn't find anything in lodash documentation , is there any good solution for this?

Thank you in Advance!!


Solution

  • You can use every() on the array produced by Object.entries() to test if every key/value pair in the expected matches the actual:

    const expectedValue = {
       city: "San Jose",
       state: "california",
       zip: "95234"
    }
    
    const actualObject = {
       address: "5543322 Adam St",
       city: "San Jose",
       state: "california",
       zip: "95234",
       country: "USA"
    }
    
    
    let test = Object.entries(expectedValue)
              .every(([key, value]) => actualObject[key] === value )
    
    console.log(test)

    It will return true if every key/pair from expectedValue exists in the actualObject and matches the value, false otherwise.

    There is an edge case where a property exists in expectedValue with a value of undefined. You can handle this by testing actualObject.hasOwnProperty(key) && actualObject[key] === value if you need to.