Open In App

Lodash _.invoke() Method

Last Updated : 16 Sep, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, lang, function, objects, numbers etc. The _.invoke() method is invoked the method at path of object. Syntax:
_.invoke(object, path, args)
Parameters: This method accepts three parameters as mentioned above and described below:
  • object: It holds the object to query.
  • path: It holds the path of the method to invoke the element.
  • args: The arguments to invoke the method with.
Return Value: This method returns the result of the invoked method. Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file. javascript
// Requiring the lodash library 
const _ = require("lodash"); 
     
// Original array 
var object = { 'p': [{ 'q': { 'r': [ 3, 5, 7, 9 ] } }] };

// Using the _.invoke() method
let invt_elem = _.invoke(object, 'p[0].q.r.slice', 3, 7);

// Printing the output 
console.log(invt_elem);
Output:
[ 9 ]
Example 2: javascript
// Requiring the lodash library 
const _ = require("lodash"); 
     
// Original array 
var object = { 'p': [{ 'q': { 'r': { 's': [ 2, 4, 6, 8, 10 ] 

} } }] };

// Using the _.invoke() method
let invt_elem = _.invoke(object, 'p[0].q.r.s.slice', 2, 5);

// Printing the output 
console.log(invt_elem);
Output:
[ 6, 8, 10 ]
Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.

Next Article

Similar Reads