如何通过比较两个数组中的书籍 ID 来添加书籍作者
2021-07-06
168
var books = [
{id: 1, title: "Javascript"},
{id: 2, title: "PHP"},
{id: 3, title: "Dart"},
{id: 4, title: "C++"}
]
var authors = [
{book_id: 1, user: {id: 1, name: "John Doe"}},
{book_id: 3, user: {id: 4, name: "Alex Rio"}},
{book_id: 4, user: {id: 42, name: "Paul Radmond"}}
]
for(var i = 0; i < books.length; i++) {
let bookAuthor = authors.find(author => {
return author.book_id === books[i].id
})
console.log(bookAuthor.user)
// Push user key from authors to current book item by book id
}
循环结果:
{
id:1,
name:"John Doe"
}
error: Uncaught TypeError: Cannot read property 'user' of undefined
在此循环中第一次找到用户,但第二次返回错误。
我如何才能正确(高效地)根据我的情况将图书用户按 ID 推送到
books
数组项?
结果必须是这样的:
var books = [
{id: 1, title: "Javascript", user: {id: 1, name: "John Doe"}},
{id: 2, title: "PHP"},
{id: 3, title: "Dart", user: {id: 4, name: "Alex Rio"}},
{id: 4, title: "C++", user: {id: 42, name: "Paul Radmond"}}
]
2个回答
你离得太近了。只需检查是否找到了作者。如果找到,则将用户对象添加到书籍对象。按照此操作-
const books = [
{id: 1, title: "Javascript"},
{id: 2, title: "PHP"},
{id: 3, title: "Dart"},
{id: 4, title: "C++"}
];
const authors = [
{book_id: 1, user: {id: 1, name: "John Doe"}},
{book_id: 3, user: {id: 4, name: "Alex Rio"}},
{book_id: 4, user: {id: 42, name: "Paul Radmond"}}
];
const result = books.map(book => {
const author = authors.find(author => author.book_id === book.id);
if (author) {
book.user = author.user;
}
return book
});
console.log(result);
.as-console-wrapper { min-height: 100% !important; top: 0}
Sajeeb Ahamed
2021-07-06
你可以按照这种方式进行
const result = books.map(book => {
const author = authors.find(author => author.book_id === book.id)
if(author) return {...book, user: author}
return book;
})
PaulShovan
2021-07-06