Skip to content

Instantly share code, notes, and snippets.

@CreatiCoding
Created July 18, 2019 14:15
Show Gist options
  • Select an option

  • Save CreatiCoding/46670f91536dd7b68fed6bb72e2993d6 to your computer and use it in GitHub Desktop.

Select an option

Save CreatiCoding/46670f91536dd7b68fed6bb72e2993d6 to your computer and use it in GitHub Desktop.
lodash group by
const _ = require('lodash');
var obj = [
{ x: 1, x1: 123, a: 2, b: 3 },
{ x: 2, x1: 5432, a: 4, b: 23 },
{ x: 1, x1: 123, a: 123, b: 324 },
];
var common_column = ['x', 'x1'];
var result = _.chain(obj)
.groupBy('x')
.map((e) => ({
..._.pick(_.first(e), common_column),
list: e.map((e) => _.omit(e, common_column)),
}))
.value();
console.log(obj);
console.log(JSON.stringify(result, null, ' '));
/*
[ { x: 1, x1: 123, a: 2, b: 3 },
{ x: 2, x1: 5432, a: 4, b: 23 },
{ x: 1, x1: 123, a: 123, b: 324 } ]
[
{
"x": 1,
"x1": 123,
"list": [
{
"a": 2,
"b": 3
},
{
"a": 123,
"b": 324
}
]
},
{
"x": 2,
"x1": 5432,
"list": [
{
"a": 4,
"b": 23
}
]
}
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment