Match object properties

OSCC · JavaScript, Object · Nov 3, 2020

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

const matches = (obj, source) =>
  Object.keys(source).every(
    key => obj.hasOwnProperty(key) && obj[key] === source[key]
  );
matches({ age: 25, hair: 'long', beard: true }, { hair: 'long', beard: true });
// true
matches({ hair: 'long', beard: true }, { age: 25, hair: 'long', beard: true });
// false

Recommended snippets & collections

  • JavaScript Comparison

    Snippet collection

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

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

  • Check object equality

    JavaScript, Object

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

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