最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Lodashunderscore: Convert array of objects to single object - Stack Overflow

programmeradmin3浏览0评论

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!

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!

Share Improve this question asked Sep 3, 2015 at 0:59 ShaharZShaharZ 3891 gold badge5 silver badges11 bronze badges 0
Add a comment  | 

5 Answers 5

Reset to default 9

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}]);

I'd do this:

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

Clear and simple.

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!"}

Updating @ry answer to a newer version of lodash:

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

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

var result = _.zipObject(
    _.pluck(A, 'key'),
    _.pluck(A, 'val')
);
发布评论

评论列表(0)

  1. 暂无评论