how to use the matcher function from the underscore library in javascript

The matcher function in the Underscore library is used to create a function that will iterate over a collection and return true for elements that match a set of properties.

Syntax

index.tsx
_.matcher(attrs)
17 chars
2 lines

Parameters:

  • attrs - An object that contains properties and their values to be matched.

Returns:

A function that takes a single argument and returns true if the object passed to it has all of the key/value pairs present in attrs.

Example:

Suppose we have an array of objects representing fruits and we want to find all the fruits that are red in color:

index.tsx
var fruits = [{ name: 'apple', color: 'red' },
              { name: 'banana', color: 'yellow' },
              { name: 'cherry', color: 'red' },
              { name: 'kiwi', color: 'brown' }];

var redFruits = _.filter(fruits, _.matcher({ color: 'red' }));

console.log(redFruits); // Output: [{ name: 'apple', color: 'red' }, { name: 'cherry', color: 'red' }]
363 chars
9 lines

In this example, we used _.matcher({ color: 'red' }) to create a function that takes an object and returns true if the object's color property is equal to 'red'. We then used this function in conjunction with underscore's filter function to return a new array of objects that have a color property equal to 'red'.

Note that the matcher function can also be used with other underscore functions such as find, reject, some, and every.

gistlibby LogSnag