lodash: mapping array to object

core picture core · Feb 18, 2016 · Viewed 114.1k times · Source

Is there a built-in lodash function to take this:

var params = [
    { name: 'foo', input: 'bar' },
    { name: 'baz', input: 'zle' }
];

And output this:

var output = {
    foo: 'bar',
    baz: 'zle'
};

Right now I'm just using Array.prototype.reduce():

function toHash(array, keyName, valueName) {
    return array.reduce(function(dictionary, next) {
        dictionary[next[keyName]] = next[valueName];
        return dictionary;
    }, {});
}

toHash(params, 'name', 'input');

Wondering if there's a lodash short-cut.

Answer

stasovlas picture stasovlas · Dec 7, 2016

Another way with lodash 4.17.2

_.chain(params)
    .keyBy('name')
    .mapValues('input')
    .value();

or

_.mapValues(_.keyBy(params, 'name'), 'input')

or with _.reduce

_.reduce(
    params,
    (acc, { name, input }) => ({ ...acc, [name]: input }),
    {}
)