简体   繁体   中英

Lodash/underscore: Convert array of objects to single object

I have an array of objects that looks like so:

var A = [{key:"key1",val:1},{key:"key2",val:2},...,{key:"keyn",val:n}]

And I want to transform A to an object:

{
    key1: 1,
    key2: 2,
    ...
    keyn: n
}

This usecase has never come up, but I was thinking of doing mapKeys and then mapValues and I feel there's a simpler answer. Thanks!

You don't really need lodash to achieve that. Just do this with array.reduce() . See code sample below:

function transformArray(arraySrc){
    return arraySrc.reduce(function(prev, curr){
        prev[curr.key] = curr.val;
        return prev;
    }, {});
}

transformArray([{key:"key1",val:1},{key:"key2",val:2},{key:"key3",val:3}]);

There may be a built-in way that I can't find, but:

var result = _.zipObject(
    _.pluck(A, 'key'),
    _.pluck(A, 'val')
);

I'd do this:

var result = _(A).keyBy('key').mapValues('val').value();

Clear and simple.

Updating @ry answer to a newer version of lodash:

var result = _.zipObject(
    _.map(A, 'key'),
    _.map(A, 'val')
);

After spending some time looking for a lodash solution for this same problem (and not finding any), I came up with this small helper function:

// Array<{}> => {}; ie.: [{ a: 1, }, { b: 2 }] => { a: 1, b: 2 }
export const objectsListToMergedObject = (...objectsList) =>
    Object.assign({}, ...objectsList);

The best way is to use _.extend.

let list = [{"foo":"bar"},{"baz":"faz"},{"label":"Hello, World!"}];
let singleObject = _.extend.apply({}, list);

Output:

{foo: "bar", baz: "faz", label: "Hello, World!"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM