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.
invoke
method to achieve the same result as the map
function?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>
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])
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.
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.
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.
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)
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With