How does the _.invoke method work in Lodash?

Background

From the documentation on the invoke method, I read:

Calls a method named MethodName for each item in the collection, returning an array of the results of each method called

Thus, I assumed that the following code will be synonymous, but it is not:

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

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

In this case, the method invokecreates an array of strings, and the map method returns an array of elements c fieldNameremoved from each element.

Questions

  • How to use a method invoketo achieve the same result as a function map?
  • Why did invokereturn an 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>
Run codeHide result
+4
source share
4
var result = _.invoke(items, fn, extraArgs)

var result = [];
for (var i=0; i<items.length; i++) {
  result.push( fn.apply(items[i], extraArgs) );
}

, , ,

_.invoke(items, function() {
  return _.omit(this, 'id');
})

, item , this, .

+7

lodash, .

v4.11.1 _.invokeMap :

_.invokeMap([1,2,3], function () {
    console.log(this)
})
+7

invoke .

,

[
(new Date()).toString(),
(new Date()).toString(),
(new Date()).toString()
]

:

_.invoke([new Date(), new Date(), new Date()], 'toString')

map, map , invoke .

invoke , , :

var items = [{id:1, name:'foo'}, 
             {id:2, name:'bar'}, 
             {id:3, name:'baz'}, 
             {id:4, name:'qux'}];
_.invoke(items, function() { return _.omit(this, 'id') });
// => [Object {name="foo"}, Object {name="bar"}, Object {name="baz"}, Object {name="qux"}]

. map.

+2

Joe Frambach, map() .

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

_.map(collection, _.ary(_.partialRight(_.omit, 'id'), 1));
// → 
// [
//   { name: 'foo' },
//   { name: 'bar' },
//   { name: 'baz' },
//   { name: 'qux' }
// ]
+1

All Articles