yurisich
yurisich

Reputation: 7119

Map to object with an accumulator

Is there a more idiomatic way to mapToObject in lodash?

var accumulator = {};
_.map([1, 2, 3], function (number) {
    accumulator[number] = number + 1;
});

// {1: 2, 2: 3, 3: 4}

Is there a way to do this without explicitly providing an accumulator for the map function?

_.mapToObject([1, 2, 3], function (accumulator, number) { 
    return accumulator[number] = number + 1;
}

Upvotes: 2

Views: 3600

Answers (1)

Pointy
Pointy

Reputation: 413826

That's what .reduce() is for:

var accumulator = 
  _.reduce([1, 2, 3], function(acc, num) { acc[num] = num + 1; return acc; }, {});

In modern browsers there's a native .reduce() on the Array prototype that's more-or-less the same as the versions provided by lodash and Underscore.

The .map() API is for creating a new array from an existing array. If you just want to do something with each element of an array, you'd use .forEach(). The .filter() API is for making an array of selected elements of an array.

Upvotes: 5

Related Questions