我想使用books.lang
和.map()
通过语言.filter()
搜索以下数据模块。如果没有定义语言,该函数将返回所有具有相关书籍的作者。如果要求使用某种语言,则该函数仅返回以该语言翻译书籍的作者。
数据模块如下:
// data.js
const authors = [
{
id: 1,
name: "Author 1"
},
{
id: 2,
name: "Author 2"
},
{
id: 3,
name: "Author 3"
}
];
const books = [
{
id: 1,
authorId: 1,
lang: "IT",
title: "Title 1",
date: "2018-06-07"
},
{
id: 2,
authorId: 1,
lang: "EN",
title: "Title 2",
date: "2018-06-07"
},
{
id: 3,
authorId: 2,
lang: "IT",
title: "Title 1",
date: "2018-06-07"
},
{
id: 4,
authorId: 2,
lang: "FR",
title: "Title 2",
date: "2018-06-07"
},
{
id: 5,
authorId: 3,
lang: "IT",
title: "Title 1",
date: "2018-07-07"
}
];
module.exports = { authors, books };
一个常见的解决方案使用经典的for循环。但是我找不到仅使用.map()
和.filter()
并最终链接它们的正确解决方案,它无法按作者对书籍进行分组。对于每位作者,我都会创建一个books
属性来对相关书籍进行分组。
经典的工作解决方案如下:
const lang = "IT";
filtered_books = books.filter( book => lang !== null ? book.lang == lang : book.lang !== '' );
for (let i in authors) {
authors[i].books = filtered_books.filter( book => book.authorId == authors.id);
}
在这里,我会坚持使用.map()
和.filter()
解决方案:
const lang = "IT";
const selectedAuthors = books.filter( book => lang !== null ? book.lang == lang : book.lang !== '' )
.map( book => {
return authors.filter( author => {
if(author.id == book.authorId) return author.books = book; // Should I push something here?
});
});
无论是否带有lang
参数,它都不会按作者对结果书籍进行分组。
非常感谢您提供任何建议。
答案 0 :(得分:1)
我看起来好像分两个阶段进行:1)将作者与他们的书合并在一起,2)筛选出拥有指定语言书籍的作者。
const authors = [{"id":1,"name":"Author 1"},{"id":2,"name":"Author 2"},{"id":3,"name":"Author 3"}];
const books = [{"id":1,"authorId":1,"lang":"IT","title":"Title 1","date":"2018-06-07"},{"id":2,"authorId":1,"lang":"EN","title":"Title 2","date":"2018-06-07"},{"id":3,"authorId":2,"lang":"IT","title":"Title 1","date":"2018-06-07"},{"id":4,"authorId":2,"lang":"FR","title":"Title 2","date":"2018-06-07"},{"id":5,"authorId":3,"lang":"IT","title":"Title 1","date":"2018-07-07"}];
function findBooks(authors, books, lng) {
// map over the books and get their books
const combined = authors.map(author => {
const filteredBooks = lng
? books.filter(book => book.authorId === author.id && book.lang === lng)
: books.filter(book => book.authorId === author.id)
return { ...author, books: filteredBooks };
});
// if a language has been specified, return only those authors who have books
// in that language
return lng ? combined.filter(author => author.books.some(book => book.lang === lng)) : combined;
}
const authorBooks = findBooks(authors, books);
console.log(authorBooks);
const authorBooksLng = findBooks(authors, books, 'EN');
console.log(authorBooksLng);