30秒学会 JavaScript 片段 · 2022年3月14日

30秒学会 JavaScript 片段 – Matches object properties based on function

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

  • Use Object.keys() to get all the keys of the second object.
  • Use Array.prototype.every(), Object.prototype.hasOwnProperty() and the provided function to determine if all keys exist in the first object and have equivalent values.
  • If no function is provided, the values will be compared using the equality operator.

代码实现

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

翻译自:https://www.30secondsofcode.org/js/s/function-based-object-property-matches