Lodash groupby nested array

Viewed 2509

I`m trying to use the groupBy function of Lodash to reshape a nested array.

I get the book store data, where I retrieve the list of books with their title and the list of their authors.

 [
     {
        "title": "",
        "author": [
          {
            "given": "",
            "family": "",
            "affiliation": []
          },
          {
            "given": "",
            "family": "",
            "affiliation": []
          }
         ]
      },{
        "title": "",
        "author": [
          {
            "given": "",
            "family": "",
            "affiliation": []
          },
          {
            "given": "",
            "family": "",
            "affiliation": []
          }
         ]
      }
    ]

Full example with input and desired output

Then I want to group those books by authors. A book belongs to Many authors and we look for reversing the relation (Later I also which to group them by affiliation and by author, but lets stay simple for the beginning)

result = _.groupBy(result, function(item) {
   return _.map(item.author,'given')
});

My issues is that groupBy doesn`t accept an array of categories to group the item in. I need to find an alternative solution.

2 Answers
Related