javascript - 使用 JavaScript .map() 和 .filter() 按语言搜索作者/书籍数据模块
问题描述
我想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
参数,它都不会按作者对结果书进行分组。
非常感谢您的任何建议。
解决方案
我看起来像一个两阶段的通行证 - 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);
推荐阅读
- php - PHP - 与来自多个页面的实例共享静态类变量
- html - 引导选项卡 - 同一行上的多张卡片
- selenium-webdriver - 我们如何处理截断的标签或文本
- excel - Excel VBA将数据从一张表中的表格移动到另一张表中的表格
- javascript - 在表格上打印时图像消失
- swift - swift 编译器/链接器是否会自动删除未使用的方法/类/扩展等?
- mysql - 使用相同打开的连接插入超过 50 个查询
- java - 从 xml 文件中获取长值
- mysql - 用于添加当前位于不同表中的列的 SQL 查询
- python-3.x - 包 cvxpy 新语法错误汇总条目