3

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.

2 Answers 2

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
    });
  });
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Very good suggestion I like the Pandas like syntax. It seems promising to me in terms of manipulating json files as a Dataset.
Unfortunately datalib is concerned only by "flat" tabular data. So it can`t solver the problem for nested arrays. see discussion on GitHub

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.