Jlearner
Jlearner

Reputation: 45

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!!

Upvotes: 2

Views: 2215

Answers (2)

Ori Drori
Ori Drori

Reputation: 191976

Lodash has the _.isMatch() function:

Performs a partial deep comparison between object and source to determine if object contains equivalent property values.

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

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

const result = _.isMatch(actualObject, expectedValue)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

Upvotes: 0

Mark
Mark

Reputation: 92440

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.

Upvotes: 4

Related Questions