Reputation: 25645
I'm using lodash map in this way
const newCollection = _.map(
responseJson.OldCollection,
AddDetailsToSingleItems
);
having
function AddDetailsToSingleItems (item ) {
...
}
I ask you, please, what's the right syntax to pass a parameter to this function.
I'd like to have
function AddDetailsToSingleItems (item, myNewParam ) {
...
}
(note the myNewParam
).
I don't kow how to tell to loadsh map to pass every single item to my function and to pass one more param when calling AddDetailsToSingleItems
Upvotes: 4
Views: 3637
Reputation: 629
You can create a function that knows the value of myNewParam
, but only accepts the item
parameter like this:
var myNewParam = 'param_value';
var AddDetailsFn = function(m) {
return function(item) {
return AddDetailsToSingleItems(item, m);
};
};
const newCollection = _.map(
responseJson.OldCollection,
AddDetailsFn(myNewParam)
);
This way, _.map
only sees a function that takes a single parameter. The AddDetailsFn
returns a function that takes a single parameter, but already has the value of myNewParam
captured. You can also be more succinct with:
const newCollection = _.map(
responseJson.OldCollection,
function(item) { return AddDetailsToSingleItems(item, myNewParam); }
);
Upvotes: 2
Reputation: 61512
You haven't explained where myNewParam
is coming from, but I assume you have that data somewhere.
Lodash map (just like normal JavaScript map) accepts a function as its second argument to be run on all elements of the supplied list. You can just pass an anonymous function:
_.map(
responseJson.OldCollection,
item => AddDetailsToSingleItems(item, myNewParam)
);
Upvotes: 5