Q:

Convert array of objects to grouped object with values in lodash

I’m looking for a compact lodash solution to take an array of objects and then create a new object with the keys of the objects in the array and the unique values for each key.
[
    {
        color: "black",
        type: "bag",
    },
    {
        color: "red",
        type: "pants",
    },
    {
        color: "black",
        type: "jacket",
    },
]

Desired output:
{
    color: ["black", "red"],
    type: ["bag", "pants", "jacket"],
}

Thanks!

A:

You can solve this using lodash#flatMap with a lodash#toPairs iteratee, to create a flattened version of an array pair of keys and values. Use lodash#groupBy with an iteratee function that removes the key of the array pairs, Array#shift, and use such value as the grouping key for the collection. Lastly, use lodash#mapValues with an iteratee that is composed of lodash#flatten and lodash#uniq, to flatten the array and only get the unique values for each grouped array. Note that the function composition uses lodash#flow to compose successive function arguments to form one functional result.
var result = _(array)
  .flatMap(_.toPairs)
  .groupBy(v => v.shift())
  .mapValues(_.flow(_.flatten, _.uniq))
  .value();

var array = [
    {
        color: "black",
        type: "bag",
    },
    {
        color: "red",
        type: "pants",
    },
    {
        color: "black",
        type: "jacket",
    }
];

var result = _(array)
  .flatMap(_.toPairs)
  .groupBy(v => v.shift())
  .mapValues(_.flow(_.flatten, _.uniq))
  .value();
  
console.log(result);
.as-console-wrapper{min-height:100%;top:0}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

