【发布时间】:2020-10-01 06:59:25
【问题描述】:
这就是我所拥有的
const users = [
{ id: 1, name: 'Mike', postIds: [11, 22] },
{ id: 2, name: 'Dan', postIds: [33] },
{ id: 3, name: 'Lance', postIds: [44] },
];
const posts = [
{ id: 11, title: 'How good is he' },
{ id: 22, title: 'How fast is he' },
{ id: 33, title: 'How to make it faster' },
{ id: 44, title: 'How can he do it' },
];
这就是我需要在输出中获得的内容
const expectedResult = [
{
id: 1,
name: 'Mike',
posts: [
{ id: 11, title: 'How good is he' },
{ id: 22, title: 'How fast is he' },
]
},
{
id: 2,
name: 'Dan',
posts: [{ id: 33, title: 'How to make it faster' }]
},
{
id: 3,
name: 'Lance',
posts: [{ id: 44, title: 'How can he do it' }]
},
]
这就是我尝试过的。它有效,但它很愚蠢,我认为它可以在一次操作中完成。请检查我可以做些什么使它更干净
const users = [
{ id: 1, name: 'Mike', postIds: [11, 22] },
{ id: 2, name: 'Dan', postIds: [33] },
{ id: 3, name: 'Lance', postIds: [44] },
];
const posts = [
{ id: 11, title: 'How good is he' },
{ id: 22, title: 'How fast is he' },
{ id: 33, title: 'How to make it faster' },
{ id: 44, title: 'How can he do it' },
];
let updUsers = users.map(obj => ({ ...obj,
posts: [...posts]
}))
const output = updUsers.map(
user => ({
...user,
posts: user.posts.filter(
post => user.postIds.includes(post.id)
)
})
);
const expectedOut = output.map(({
id,
name,
posts
}) => ({
id,
name,
posts
}))
console.log(expOut)
【问题讨论】:
标签: javascript ecmascript-6 destructuring