简体   繁体   English

Lodash groupby嵌套数组

[英]Lodash groupby nested array

I`m trying to use the groupBy function of Lodash to reshape a nested array. 我试图使用Lodash的groupBy函数来重塑嵌套数组。

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. 我的问题是groupBy不接受一系列类别来对项目进行分组。我需要找到一个替代解决方案。

Answer Provided to me by the Datalib contributer 答案由Datalib供应商提供给我

standard JavaScript array functions 标准的JavaScript数组函数

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 使用json-groupby

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. 这个lib允许在d3.js之上构建多个分组参数,并且速度非常快。 Maybe you can benefit from it 也许你可以从中受益

https://github.com/vega/datalib https://github.com/vega/datalib

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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