Pregunta

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, 
¿Fue útil?

Solución

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;
}, {});
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top