Check Equality of Two Objects


Uncategorized

Updated Jan 17th, 2022

Not as simple as you would think.

Saw this in the the wild:

  const isEquivalent = (a: any, b: any) => {
    // Create arrays of property names
    var aProps = Object.getOwnPropertyNames(a)
    var bProps = Object.getOwnPropertyNames(b)

    // If number of properties is different,
    // objects are not equivalent
    if (aProps.length != bProps.length) {
      return false
    }

    for (var i = 0; i < aProps.length; i++) {
      var propName = aProps[i]

      // If values of same property are not equal,
      // objects are not equivalent
      if (a[propName] !== b[propName]) {
        return false
      }
    }

    // If we made it this far, objects
    // are considered equivalent
    return true
  }

Also saw recommendations to use lodash library

_.isEqual(object, other)