What is the findWhere function in Underscore.js?
Overview
We can use the findWhere() in Underscore.js to get or return the first value of a list of objects that matches the specified property.
Syntax
_findWhere(list, property)
Syntax for findWhere() function in underscore.js
Parameters
list: This is the list we want to get the element that matches the property specified.
property: This could be one or more. It is the property we want to find. We specify it using a key-value pair.
Return value
It returns an element of the object list that contains the specified property or properties. If no match is found, it returns undefined.
Example
// require the underscore packageconst _ = require("underscore")// create a listlet list = [{age: 19, name: "Doe", course: "Computer Science"},{age: 30, name: "John", course: "Public Health"},{age: 15, name: "Amaka", course: "Mathematics"},{age: 19, name: "Esther", course: "Computer Science"},]// fetch property nameconsole.log(_.findWhere(list, {name: "Doe"}))// fetch property courseconsole.log(_.findWhere(list, {course: "Computer Science"}))// fetch with more propertiesconsole.log(_.findWhere(list, {course: "Mathematics", name: "Amaka"}))// fetch non-existent propertyconsole.log(_.findWhere(list, {course: "English"}))
Explanation
- Line 2: We require the
underscorepackage. - Line 5: We create a list.
- Lines 12–19: We use the
findWhere()method to find some elements of the list based on the specified properties. Next, we print the results to the console.