[英]forEach loop returns undefined value
I've dummy data (books) which I want see from graphiql gui . 我想从graphiql gui看到虚拟数据(书籍)。 But when I use a forEach
loop to iterate through the books, looking for a specific id
, it's returning undefined values, but if I use a normal for
loop it works fine. 但是当我使用forEach
循环遍历书籍,寻找特定的id
,它返回未定义的值,但是如果我使用普通的for
循环它可以正常工作。
This is my code: 这是我的代码:
let books = [
{ name: 'Name of the Wind', genre: 'Horror', id: '1', authorID: '3' },
{ name: 'The Final Empire', genre: 'Fantasy', id: '2', authorID: '1' },
{ name: 'The Long Earth', genre: 'Sci-Fi', id: '3', authorID: '2' },
];
const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
book: {
type: BookType,
args: { id: { type: GraphQLString } },
//this forEach is not working
resolve(parent, args){
books.forEach( function(book) {
if(book.id == args.id) {
console.log(book);
return book;
}
});
}
}
}
});
When I print out the book data, it's showing that particular book in the console but not in the GUI response: 当我打印出书籍数据时,它会在控制台中显示该特定书籍,但不会显示在GUI响应中:
request:
{
book(id: "2") {
name
genre
}
}
response:
{
"data": {
"book": null
}
}
A return <value>
in a forEach
callback is meaningless. forEach
回调中的return <value>
是没有意义的。 The returned value goes nowhere, and the loop is not interrupted either. 返回的值无处可去,循环也不会中断。
Instead use .find
: 而是使用.find
:
return books.find(function(book) {
return book.id == args.id;
});
When performance is important, and you have lots of books, then it is better to first preprocess the books and create a Set: 当性能很重要,而且你有很多书籍时,最好先对书籍进行预处理并创建一个Set:
let books = [
{ name: 'Name of the Wind', genre: 'Horror', id: '1', authorID: '3' },
{ name: 'The Final Empire', genre: 'Fantasy', id: '2', authorID: '1' },
{ name: 'The Long Earth', genre: 'Sci-Fi', id: '3', authorID: '2' },
];
let bookIds = new Set(books.map(({id}) => id));
... and then no loop is needed to know whether a book ID is valid or not: ...然后不需要循环来知道书籍ID是否有效:
return bookIds.has(args.id);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.