Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

underscore.js

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

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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"))
Using the pick() method of Underscore.js

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.

RELATED TAGS

underscore.js

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring