对于以下输入数据:
let posts = [
{
"id": 101,
"title": "Some post title"
},
{
"id": 102,
"title": "Some Another post title"
},
{
"id": 103,
"title": "Some Best post title ever"
}
]
let reviews = [
{
"postId": 101,
"user": "Chris",
"comment": "Great post!"
},
{
"postId": 101,
"user": "Jason",
"comment": "Worth reading."
},
{
"postId": 102,
"user": "Dave",
"comment": "Waste of time"
}
]
我想返回此结果数据:
let result = [{ id: 101, title: "Some post title", reviews: [{ user: "John", Comment: "Great post!" }] }]
只能获取值,但需要没有id的评论数组,并且应该位于带有ID和标题的新结果中
答案 0 :(得分:0)
将map
与filter
一起使用:
let posts = [{
"id": 101,
"title": "Some post title"
},
{
"id": 102,
"title": "Some Another post title"
},
{
"id": 103,
"title": "Some Best post title ever"
}
]
let reviews = [{
"postId": 101,
"user": "Chris",
"comment": "Great post!"
},
{
"postId": 101,
"user": "Jason",
"comment": "Worth reading."
},
{
"postId": 102,
"user": "Dave",
"comment": "Waste of time"
}
]
const res = posts.map(({
id,
title
}) => ({
id,
title,
reviews: reviews.filter(({
postId
}) => postId == id).map(({
user,
comment
}) => ({
user,
comment
}))
}));
console.log(res);