4

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???

2 Answers 2

3

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)));
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.