What is the pick() function in Underscore.Js?

Overview

Underscore.js is a library used to manipulate arrays and objects in JavaScript. With the pick() method, we can filter the properties of an object and return only some specified ones.

Syntax

_.pick(object, *property)
Syntax for pick() method

Parameters

  • object: This is the object whose properties we want to filter.
  • *property: This is a property we want to return. It can be one or more.

Return value

This function returns an object with only some properties specified.

Example

// require underscore
const _ = require("underscore")
// create some objects
let obj1 = {one: 1, two: 2, three: 3, four: 4}
let obj2 = {name: "nodejs", package: "underscore", tag: "_"}
let obj3 = {a: "Apple", b: "Banana"}
let obj4 = {M: "Monday", T: "Tuesday", W: "Wednesday"}
// pick or select some properties
console.log(_.pick(obj1, "one"))
console.log(_.pick(obj2, "package", "tag"))
console.log(_.pick(obj3, "a", "b"))
console.log(_.pick(obj4, "T", "M"))

Explanation

  • Line 2: We require the underscore package.
  • Lines 5–8: We create some objects, obj1, obj2, obj3, and obj4. We give them some properties and values.
  • Line 11: We use the pick() method to filter "one" property of the object obj1 and log the result to the console.
  • Line 12: We use the pick() method to select the properties, "package" and "tag", of obj2 and print the result to the console.
  • Line 13: We use the pick() method to filter the properties, "a" and "b", of obj4 and print the result to the console.
  • Line 14: We select the properties, "T" and "M", of obj4 and log the result to the console.

Free Resources