Created
July 18, 2019 14:15
-
-
Save CreatiCoding/46670f91536dd7b68fed6bb72e2993d6 to your computer and use it in GitHub Desktop.
lodash group by
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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