Convert array of objects to object of arrays using lodash

别来无恙 提交于 2019-12-06 09:44:20

Here's a solution using lodash that maps across the keys and plucks the values for each key from the data before finally using _.zipOobject to build the result.

var keys = _.keys(data[0]);

var result = _.zipObject(keys, _.map(keys, key => _.map(data, key)));

Look for _.map here

input = [
    {a: 1, b: 2, c:3},
    {a: 4, b: 5, c:6},
    {a: 7, b: 8, c:9}
];

output = {};

_.map(input, function(subarray){
    _.map(subarray, function(value, key){
            output[key] || (output[key] = []);
            output[key].push(value);
    });
});

console.log(output);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!