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

  • Get nested value in object based on array of keys

    Gets the target value in a nested JSON object, based on the keys array.

    JavaScript, Object · Oct 19, 2020

  • Find first matching key

    Finds the first key that satisfies the provided testing function. Otherwise undefined is returned.

    JavaScript, Object · Oct 22, 2020