using lodash .groupBy. how to add your own keys for grouped output? using lodash .groupBy. how to add your own keys for grouped output? javascript javascript

using lodash .groupBy. how to add your own keys for grouped output?


You can do it like this in both Underscore and Lodash (3.x and 4.x).

var data = [{  "name": "jim",  "color": "blue",  "age": "22"}, {  "name": "Sam",  "color": "blue",  "age": "33"}, {  "name": "eddie",  "color": "green",  "age": "77"}];console.log(  _.chain(data)    // Group the elements of Array based on `color` property    .groupBy("color")    // `key` is group's name (color), `value` is the array of objects    .map((value, key) => ({ color: key, users: value }))    .value());
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>