gpt4 book ai didi

javascript - 使用 JavaScript .map() 和 .filter() 按 lang 搜索作者/书籍数据模块

转载 作者:行者123 更新时间:2023-12-03 00:51:14 25 4
gpt4 key购买 nike

我想使用 .map().filter() 按语言 books.lang 搜索以下数据模块。如果没有定义语言,该函数将返回具有相关书籍的所有作者。如果请求某种语言,则该函数仅返回将书籍翻译成该语言的作者。

数据模块如下:

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

关于javascript - 使用 JavaScript .map() 和 .filter() 按 lang 搜索作者/书籍数据模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53031858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com