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 underscoreconst _ = require("underscore")// create some objectslet 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 propertiesconsole.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
underscorepackage. - Lines 5–8: We create some objects,
obj1,obj2,obj3, andobj4. We give them some properties and values. - Line 11: We use the
pick()method to filter"one"property of the objectobj1and log the result to the console. - Line 12: We use the
pick()method to select the properties,"package"and"tag", ofobj2and print the result to the console. - Line 13: We use the
pick()method to filter the properties,"a"and"b", ofobj4and print the result to the console. - Line 14: We select the properties,
"T"and"M", ofobj4and log the result to the console.