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.
_findWhere(list, property)
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.
It returns an element of the object list that contains the specified property or properties. If no match is found, it returns undefined
.
// 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"}))
underscore
package.findWhere()
method to find some elements of the list based on the specified properties. Next, we print the results to the console.