问题
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.
回答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
});
});
回答2:
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
来源:https://stackoverflow.com/questions/45468986/lodash-groupby-nested-array