Convert array of objects to object of arrays using lodash

為{幸葍}努か 提交于 2020-01-02 11:14:04

问题


The title is a little bit confusing but I essentially want to convert this:

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

into:

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

using lodash (requirement). Any ideas???


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/36638450/convert-array-of-objects-to-object-of-arrays-using-lodash

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