Open In App

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: 

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:




// 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.




// 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:

{}
Article Tags :