【问题标题】:Lodash groupby nested arrayLodash groupby 嵌套数组
【发布时间】:2017-08-02 18:59:59
【问题描述】:

我正在尝试使用 Lodash 的 groupBy 函数来重塑嵌套数组。

我获得了书店数据,在那里我检索了包含书名和作者列表的书籍列表。

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

Full example with input and desired output

然后我想按作者对这些书进行分组。一本书属于许多作者,我们正在寻找扭转关系 (稍后我也会按所属机构和作者对它们进行分组,但一开始就保持简单)

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

我的问题是 groupBy 不接受将项目分组的类别数组。我需要找到替代解决方案。

【问题讨论】:

    标签: javascript json lodash


    【解决方案1】:

    Datalib contributer 提供给我的答案

    标准 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;
    }, {});
    

    替代解决方案

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

    【讨论】:

      【解决方案2】:

      这个库支持在 d3.js 之上构建多个分组参数,并且速度非常快。也许你可以从中受益

      https://github.com/vega/datalib

      【讨论】:

      • 非常好的建议我喜欢Pandas like syntax。在将 json 文件作为数据集进行操作方面,这对我来说似乎很有希望。
      • 不幸的是,datalib 只关注“平面”表格数据。所以它不能解决嵌套数组的问题。 see discussion on GitHub
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-28
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 2017-06-15
      • 2019-04-14
      • 2017-09-01
      相关资源
      最近更新 更多