Lodash groupby嵌套数组 [英] Lodash groupby nested array

查看:162
本文介绍了Lodash groupby嵌套数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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": []
          }
         ]
      }
    ]

具有输入和所需输出的完整示例

然后,我想按作者对这些书进行分组.一本书属于许多作者,我们正在寻求扭转这种关系 (后来我也按隶属关系和作者对它们进行分组,但让我们从头开始要保持简单)

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

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

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

推荐答案

Datalib贡献者

标准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

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

这篇关于Lodash groupby嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆