Underscore.js _.pickWhen() Method

The _.pickWhen() method returns a copy of the object containing those properties for which the given predicate function returns true. The predicate function is invoked with each property value.
Syntax:
_.pickWhen( Object_name, predicate_func );
Parameters:
- Object_name: Object from which the key/value pair is to be picked.
- predicate_func: Given function which contains the conditions for properties is to be picked
Return Value: This method returns a copy of the object after containing properties.
Note: This will not work in normal JavaScript because it requires the underscore.js contrib library to be installed.
Underscore.js contrib library can be installed using npm install underscore-contrib –save.
Example 1:
Javascript
// Defining underscore contrib variable var _ = require('underscore-contrib'); var obj = { 1: "Gfg1", 2: "Gfg2", 3: "Gfg3"}; var val = _.pickWhen(obj, function (id) { return id == "Gfg1" }); console.log(val); |
Output:
{ '1': 'Gfg1' }
Example 2: If no property is found in the object, this method picks nothing.
Javascript
// Defining underscore contrib variable var _ = require('underscore-contrib'); var obj = { 1: "Gfg1", 2: "Gfg2", 3: "Gfg3"}; var val = _.pickWhen(obj, function (id) { return id == "Gfg4" }); console.log(val); |
Output:
{}
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!



