Convert array of objects to object of arrays using

2019-05-18 16:07发布

问题:

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