简体   繁体   中英

Lodash groupby nested array

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.

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
    });
  });

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM