如何在lodash forEach中创建一个回调函数来填充数组? [英] How can I make a callback function in the lodash forEach populate an array?
问题描述
我有以下代码:
$scope.option.cityMap = data.reduce(function (rv, v) {
rv[v.cityId] = v;
return rv;
}, {});
有人可以告诉我如何使用_.lodash forEach实现此功能吗?我看了看文档,但是我不确定如何实现回调函数,所以它会创建一个数组.
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,
推荐答案
使用功能助手,所有解决方案的效率都低于命令式":
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).
您还可以使用 _.zipObject
:
You can also use _.zipObject
:
var cityMap = _(data).map(data, function (v) {
return [v.cityId, v];
}).zipObject().value();
或 reduce
,因为我们没有复制累加器rv
(从某种意义上讲是作弊),它也应该非常有效.
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;
}, {});
这篇关于如何在lodash forEach中创建一个回调函数来填充数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!