Search code examples
javascriptlodash

Lodash map with function: how to pass to function another parameter?


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


Solution

  • 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)
    );