【发布时间】:2021-11-11 20:48:58
【问题描述】:
正在寻找更优化的方法。
资源数组:
const users = [
{ id: 1, name: 'Vasya', postIds: [11, 22] },
{ id: 2, name: 'Petya', postIds: [33] },
{ id: 3, name: 'Roma', postIds: [44] },
];
const posts = [
{ id: 11, title: 'How to eat' },
{ id: 22, title: 'How to drink' },
{ id: 33, title: 'How to breath' },
{ id: 44, title: 'How to swim' },
];
预期结果
const expectedResult = [
{
id: 1,
name: 'Vasya',
posts: [
{ id: 11, title: 'How to eat' },
{ id: 22, title: 'How to drink' },
]
},
{
id: 2,
name: 'Petya',
posts: [{ id: 33, title: 'How to breath' },]
},
{
id: 3,
name: 'Roma',
posts: [{ id: 44, title: 'How to swim' }]
},
]
我在做什么:
const expectedOutput = users.map(({id,name,postIds})=>({id,name,posts:posts.filter(post=>postIds.includes(post.id))}))
问题是 - 我正在做太多的迭代(映射、过滤和包含),我认为有可能以更漂亮的方式来做。对任何重构的想法都会很感激
【问题讨论】:
标签: javascript arrays json filter reduce