Matches Object Properties Based on Function

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the matchesWith function in JavaScript. The purpose of this lab is to learn how to compare two objects and determine if they contain equivalent property values based on a provided function. We will be using Object.keys(), Array.prototype.every(), and Object.prototype.hasOwnProperty() to accomplish this task.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") subgraph Lab Skills javascript/variables -.-> lab-28337{{"`Matches Object Properties Based on Function`"}} javascript/data_types -.-> lab-28337{{"`Matches Object Properties Based on Function`"}} javascript/arith_ops -.-> lab-28337{{"`Matches Object Properties Based on Function`"}} javascript/comp_ops -.-> lab-28337{{"`Matches Object Properties Based on Function`"}} javascript/array_methods -.-> lab-28337{{"`Matches Object Properties Based on Function`"}} end

Matching Object Properties with a Function

To start practicing coding, open the Terminal/SSH and type node.

This function compares two objects and checks if the first object contains equivalent property values to the second one. It does so based on a provided function.

To use this function, follow these steps:

  • Use Object.keys() to retrieve 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]
  );

Here is an example of how to use this function:

const isGreeting = (val) => /^h(?:i|ello)$/.test(val);
matchesWith(
  { greeting: "hello" },
  { greeting: "hi" },
  (oV, sV) => isGreeting(oV) && isGreeting(sV)
); // true

This example checks if the two objects have equivalent values for the greeting property. It uses the isGreeting function to ensure that both values are valid greetings.

Summary

Congratulations! You have completed the Matches Object Properties Based on Function lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like