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
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
2 Answers
Reset to default 5You haven't explained where myNewParam
is ing 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)
);
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); }
);