Underscore.js _.omitWhen() Method

The _.omitWhen() method returns a copy of the object omitting those properties for which the given predicate function returns true. The predicate function is invoked with each property value.

Syntax:

_.omitWhen( Object_name, predicate_func );

Parameters: 

  • Object_name: Object from which the key/value pair is to be omitted.
  • predicate_func: Given function which contains the conditions for properties is to be omitted

Return Value: This method returns a copy of the object after omitting 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

filter_none

edit
close

play_arrow

link
brightness_4
code

// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
var obj = {
    1: "Gfg1",
    2: "Gfg2",
    3: "Gfg3"
};
  
var val=_.omitWhen(obj, function (id) 
         { return id == "Gfg2" });
console.log(val);

chevron_right


Output:

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

Example 2: If no property is found in the object, this method omits nothing.

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
var obj = {
    1: "Gfg1",
    2: "Gfg2",
    3: "Gfg3"
};
  
var val=_.omitWhen(obj, function (id) 
          { return id == "Gfg4" });
console.log(val);

chevron_right


Output:

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

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.