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 package
const _ = require("underscore")
// create a list
let 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 name
console.log(_.findWhere(list, {name: "Doe"}))
// fetch property course
console.log(_.findWhere(list, {course: "Computer Science"}))
// fetch with more properties
console.log(_.findWhere(list, {course: "Mathematics", name: "Amaka"}))
// fetch non-existent property
console.log(_.findWhere(list, {course: "English"}))

Explanation

  • Line 2: We require the underscore package.
  • 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.

Free Resources