Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the _.invoke method work in Lodash?

Background

From the documentation about the invoke method, I read:

Invokes the method named by methodName on each element in collection, returning an array of the results of each invoked method

Thus, I assumed that the following code would be synonymous, but this is not the case:

_.map(items, function(item) {
    return _.omit(item, 'fieldName');
})

_.invoke(items, _.omit, 'fieldName');

In this case, the invoke method produces an array of strings, while the map method returns an array of items with fieldName removed from each item.

Questions

  • How can one use the invoke method to achieve the same result as the map function?
  • Why did invoke return the array of strings in this particular situation?

var items = [{id:1, name:'foo'}, 
             {id:2, name:'bar'}, 
             {id:3, name:'baz'}, 
             {id:4, name:'qux'}];

console.log(
    _.invoke(items, _.omit, 'id')
);

console.log(
    _.map(items, function(item) {
        return _.omit(item, 'id');
    })
);
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.3.1/lodash.min.js"></script>
like image 695
Pete Avatar asked Mar 05 '15 22:03

Pete


People also ask

What is _ get?

The _. get() function is an inbuilt function in the Underscore. js library of JavaScript which is used to get the value at the path of object. If the resolved value is undefined, the defaultValue is returned in its place. Syntax: _.get(object, path, [defaultValue])

What is lodash UnderScore?

The lodash and UnderScore both are utility libraries from JavaScript which helps make it easier by providing utils which makes, working with arrays, numbers, objects, and strings much easier. They provide a group of tools used for common programming operations having a strong functional programming task.

How does lodash get work?

get() method in Lodash retrieves the object's value at a specific path. If the value is not present at the object's specific path, it will be resolved as undefined . This method will return the default value if specified in such a case.

How check if array is empty lodash?

The Lodash _. isEmpty() Method Checks if the value is an empty object, collection, map, or set. Objects are considered empty if they have no own enumerable string keyed properties. Collections are considered empty if they have a 0 length.


1 Answers

Make sure to note which version of lodash you are using.

v4.11.1 uses _.invokeMap when operating over a collection:

_.invokeMap([1,2,3], function () {
    console.log(this)
})
like image 150
cheshireoctopus Avatar answered Oct 17 '22 09:10

cheshireoctopus