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;
}, {});