最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Lodash map with function: how to pass to function another parameter? - Stack Overflow

programmeradmin2浏览0评论

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

Share Improve this question edited Mar 16, 2018 at 15:46 realtebo asked Mar 16, 2018 at 15:43 realteborealtebo 25.7k45 gold badges126 silver badges216 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

You 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); }
);
发布评论

评论列表(0)

  1. 暂无评论