javascript - 如何使一个数组的属性成为另一个数组的属性(代码优化)
问题描述
这就是我所拥有的
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)
解决方案
posts
您可以在映射时进行过滤,users
而不是将其作为第二遍进行。
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 expOut = users.map(({id, name, postIds}) => ({ id, name,
posts: posts.filter(({id}) => postIds.includes(id))
}))
console.log(expOut)
推荐阅读
- angular - 如何使用 PM2 流程启动/服务 Angular?
- angularjs - 获取标题的文本并将其分配给变量 Protractor
- google-maps - 获取特定点与谷歌地图上绘制的线之间的距离
- python - 为什么在加载大数据并且 RAM 内存不足时使用数据库(redis、SQL)会有所帮助?
- powershell - 如何从powershell中的配置文件中获取变量
- c++ - STL 容器的自定义分配器错误
- excel - 无法使用 VBA 复制 Excel 地图图表
- pandas - 将 pandas 数据帧与区间数据(自上而下)相结合,并创建具有最小可能区间的新 df
- xamarin - 如何在 Xamarin.forms 中显示来自视图模型的警报视图
- python - 用于函数式编程的 Pythonic 风格