How can I make a callback function in the lodash forEach populate an array?

余生颓废 提交于 2019-12-11 12:18:04

问题


I have the following code:

$scope.option.cityMap = data.reduce(function (rv, v) {
                       rv[v.cityId] = v;
                       return rv;
                   }, {});

Can someone tell me how I can implement this with the _.lodash forEach ? I have looked at the docs but I am not sure how to implement the callback function so it creates an array.

$scope.option.cityMap = _.forEach(data, 

回答1:


Using the functional helpers all solutions are less efficient than "imperative style":

var cityMap = {};
var len = data.length;
for (var i = 0; i < len; i++) {
  cityMap[data[i].cityId] = data[i];
}
// return cityMap;

If performance is really an issue, make a function from above. It's pure and functional, if looked from outside (data in, data out, no side-effects).

You can also use _.zipObject:

var cityMap = _(data).map(data, function (v) {
  return [v.cityId, v];
}).zipObject().value();

or reduce, as we are not copying the accumulator rv (cheating in a sense), it should be quite efficient as well.

var cityMap = _.reduce(data, function (rv, v) {
  rv[v.cityId] = v;
  return rv;
}, {});


来源:https://stackoverflow.com/questions/21450360/how-can-i-make-a-callback-function-in-the-lodash-foreach-populate-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!