Thursday, September 18, 2025
HomeLanguagesJavascriptUnderscore.js _.selectKeys() Method

Underscore.js _.selectKeys() Method

The _.selectKeys() method returns a copy of obj containing only the properties listed in the given array.

Syntax:

_.omitWhen( Object_name, array );

Parameters: 

  • Object_name: Object from which the key/value pair is to be selected.
  • array: Given array containing the properties to be listed.

Return Value: This method returns a copy of the object containing the properties listed.

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 = _.selectKeys(obj, [1, 3]);
console.log(val);


Output:

{ '1': 'Gfg1', '3': 'Gfg3' }

Example 2: If no property is found in the object, this method returns an empty object.

Javascript




// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
var obj = {
    1: "Gfg1",
    2: "Gfg2",
    3: "Gfg3"
};
  
var val = _.selectKeys(obj, [4]);
console.log(val);


Output:

{}
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen 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!
RELATED ARTICLES

Most Popular

Dominic
32299 POSTS0 COMMENTS
Milvus
84 POSTS0 COMMENTS
Nango Kala
6660 POSTS0 COMMENTS
Nicole Veronica
11833 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11895 POSTS0 COMMENTS
Shaida Kate Naidoo
6779 POSTS0 COMMENTS
Ted Musemwa
7051 POSTS0 COMMENTS
Thapelo Manthata
6735 POSTS0 COMMENTS
Umr Jansen
6741 POSTS0 COMMENTS