Reputation: 24562
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,
Upvotes: 1
Views: 4045
Reputation: 12123
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;
}, {});
Upvotes: 1