How can I do a shallow comparison of the properties of two objects with Javascript or lodash?

Samantha J T Star picture Samantha J T Star · Mar 8, 2014 · Viewed 42.8k times · Source

Is there a way I can do a shallow comparison that will not go down and compare the contents of objects inside of objects in Javascript or lodash? Note that I did check lodash, but it appears to perform a deep comparison which I don't want to do.

var a = { x: 1, y: 2}
var b = { x: 1, y: 3}

Is there some way for example to compare a and b?

Answer

dhilt picture dhilt · Sep 14, 2018

Simple ES6 approach:

const shallowCompare = (obj1, obj2) =>
  Object.keys(obj1).length === Object.keys(obj2).length &&
  Object.keys(obj1).every(key => obj1[key] === obj2[key]);

Here I added the object keys amount equality checking for the following comparison should fail (an important case that usually does not taken into the account):

shallowCompare({ x: 1, y: 3}, { x: 1, y: 3, a: 1}); // false

2019 Update. Per Andrew Rasmussen' comment we also need to take into account undefined case. The problem with the previous approach is that the following comparison returns true:

({ foo: undefined })['foo'] === ({ bar: undefined })['foo'] // true

So, explicit keys existence check is needed. And it could be done with hasOwnProperty:

const shallowCompare = (obj1, obj2) =>
  Object.keys(obj1).length === Object.keys(obj2).length &&
  Object.keys(obj1).every(key => 
    obj2.hasOwnProperty(key) && obj1[key] === obj2[key]
  );