Skip to content

Instantly share code, notes, and snippets.

@hungdev
Last active October 9, 2018 02:04
Show Gist options
  • Select an option

  • Save hungdev/10d3a56f479e6b7b82858a4dbf8f0185 to your computer and use it in GitHub Desktop.

Select an option

Save hungdev/10d3a56f479e6b7b82858a4dbf8f0185 to your computer and use it in GitHub Desktop.
GroupBy

https://stackoverflow.com/questions/23600897/using-lodash-groupby-how-to-add-your-own-keys-for-grouped-output

let _ = require('lodash');
let $$ = require('eyes');



const data = [
  {
    "id": 6,
    "post": 23,
    "parent": 5,
    "author": 1,
  },
  {
    "id": 5,
    "post": 23,
    "parent": 0,
    "author": 1,
  },
  {
    "id": 4,
    "post": 23,
    "parent": 2,
    "author": 1,
  },
  {
    "id": 2,
    "post": 23,
    "parent": 0,
    "author": 1,
  }
]

  var result = _(data)
            .groupBy(x => x.parent)
            .map((value, key) => ({parent: key, child: value}))
            .value();
console.log($$.inspect(result) );

result

[
    {
        parent: '0',
        child: [
            {
                id: 5,
                post: 23,
                parent: 0,
                author: 1
            },
            {
                id: 2,
                post: 23,
                parent: 0,
                author: 1
            }
        ]
    },
    {
        parent: '2',
        child: [
            {
                id: 4,
                post: 23,
                parent: 2,
                author: 1
            }
        ]
    },
    {
        parent: '5',
        child: [
            {
                id: 6,
                post: 23,
                parent: 5,
                author: 1
            }
        ]
    }
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment