javascriptjsonchai

Is it possible to compare two objects only between the keys / properties they both share?


So I have two objects

address: {
  id: 1234,
  city: "foo",
  country: "bar",
  name: "baz"
}

and

defaultAddress: { 
  id: 1234,
  city: "foo",
  country: "bar",
  firstName: "ba",
  lastName: "z"
}

If I try to do a straight up comparison / assertion between them, i.e.

expect(address).to.contain(defaultAddress)

(or the other way around), it'll fail because each contains fields the other does not

(AssertionError: expect {address} to have a property 'firstName')

I only want to comparing the values in the keys they both share. Is it possible to do something like that programmatically?


Solution

  • You're trying to match the objects on the subset of shared keys. This can be done as follows.

    for(const key in address) {
      if(typeof defaultAddress[key] !== 'undefined') {
        expect(address[key]).to.equal(defaultAddress[key])
      }
    }
    

    Also have a look at this answer.