Matches object properties based on function

JavaScript, Object · Oct 21, 2020

Compares two objects to determine if the first one contains equivalent property values to the second one, based on a provided function.

const matchesWith = (obj, source, fn) =>
  Object.keys(source).every(key =>
    obj.hasOwnProperty(key) && fn
      ? fn(obj[key], source[key], key, obj, source)
      : obj[key] == source[key]
  );
const isGreeting = val => /^h(?:i|ello)$/.test(val);
matchesWith(
  { greeting: 'hello' },
  { greeting: 'hi' },
  (oV, sV) => isGreeting(oV) && isGreeting(sV)
); // true

More like this

  • JavaScript Comparison

    Comparing values in JavaScript is one of the most common tasks, yet it has a lot of things you should bear in mind.

    Collection · 11 snippets

  • Match object properties

    Compares two objects to determine if the first one contains equivalent property values to the second one.

    JavaScript, Object · Nov 3, 2020

  • Omit object properties based on function

    Omits the key-value pairs corresponding to the keys of the object for which the given function returns falsy.

    JavaScript, Object · Oct 21, 2020

  • Check object equality

    Performs a deep comparison between two values to determine if they are equivalent.

    JavaScript, Object · Oct 13, 2021