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.tsx17 chars2 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.tsx363 chars9 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