Lodash groupby nested array

为君一笑 提交于 2019-12-10 18:51:39

问题


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.


回答1:


Answer Provided to me by the Datalib contributer

standard JavaScript array functions

var byAuthor = books.reduce(function(authors, book) {
  book.author.forEach(function(author) {
    var name = author.family;
    var booksByAuthor = authors[name] || (authors[name] = []);
    booksByAuthor.push(book);
  });
  return authors;
}, {});

Alternative solution

Using json-groupby library

const groupBy = require('json-groupby');

// create a temporary array `authors`
  byBook.forEach(function(item) {
      item.authors = item.author.map(function(x) {
         return x.family;
      })
  });

// groupby authors
  byAuthor= groupBy(byBook, ['authors']);

// delete the temporary array
  Object.keys(byAuthor).forEach(function (key){
    byAuthor[key].forEach(function (item){
      delete item.authors
    });
  });



回答2:


This lib enables multiple grouping parameters build on top of d3.js and is blazing fast. Maybe you can benefit from it

https://github.com/vega/datalib



来源:https://stackoverflow.com/questions/45468986/lodash-groupby-nested-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!