javascript - 如何通过另一个对象值的参数过滤特定对象值
问题描述
这是输入。在“帖子”属性中,我拥有所有帖子。我需要通过“postIds”属性过滤帖子。
const users = [
{ id: 1, name: 'Dan', postIds: [11, 22],posts:[
{ id: 11, title: 'How to make it fast' },
{ id: 22, title: 'How to make it clearly' },
{ id: 33, title: 'How to can I do it' },
{ id: 44, title: 'How to he can do it' },
]} ,
{ id: 2, name: 'Mike', postIds: [33], posts:[
{ id: 11, title: 'How to make it fast' },
{ id: 22, title: 'How to make it clearly' },
{ id: 33, title: 'How to can I do it' },
{ id: 44, title: 'How to he can do it' },
]},
{ id: 3, name: 'Lola', postIds: [44], posts: [
{ id: 11, title: 'How to make it fast' },
{ id: 22, title: 'How to make it clearly' },
{ id: 33, title: 'How to can I do it' },
{ id: 44, title: 'How to he can do it' },
]}
输出应该是这样的:
const users = [
{ id: 1, name: 'Dan', postIds: [11, 22],posts:[
{ id: 11, title: 'How to make it fast' },
{ id: 22, title: 'How to make it clearly' },
] ,
{ id: 2, name: 'Mike', postIds: [33], posts:[
{ id: 33, title: 'How to can I do it' },
]},
{ id: 3, name: 'Lola', postIds: [44], posts: [
{ id: 44, title: 'How to he can do it' },
]}
我确实相信我必须使用“过滤器”和“一些”,但我尝试过的选项并不相关:
const filterUserPosts = users.filter(obj=>obj.posts.id===obj.some(postIds))
什么是最好的选择?
解决方案
您要过滤的数组是obj.posts
,而不是updUsers
(我假设与 相同users
)。
您需要循环users
过滤它们的每个posts
属性。
您可以使用includes()
来判断帖子的 id 是否在postIds
.
const users = [
{ id: 1, name: 'Dan', postIds: [11, 22],posts:[
{ id: 11, title: 'How to make it fast' },
{ id: 22, title: 'How to make it clearly' },
{ id: 33, title: 'How to can I do it' },
{ id: 44, title: 'How to he can do it' },
]} ,
{ id: 2, name: 'Mike', postIds: [33], posts:[
{ id: 11, title: 'How to make it fast' },
{ id: 22, title: 'How to make it clearly' },
{ id: 33, title: 'How to can I do it' },
{ id: 44, title: 'How to he can do it' },
]},
{ id: 3, name: 'Lola', postIds: [44], posts: [
{ id: 11, title: 'How to make it fast' },
{ id: 22, title: 'How to make it clearly' },
{ id: 33, title: 'How to can I do it' },
{ id: 44, title: 'How to he can do it' },
]}];
users.forEach(u => u.posts = u.posts.filter(p => u.postIds.includes(p.id)));
console.log(users);
推荐阅读
- google-apps-script - 电子表格:“您无权调用 setNumberFormat”
- wpf - ScrollViewer 不适用于 wpf 中的 tabcontrol
- apache-camel - 阿帕奇骆驼日期
- ubuntu - 无法使用 Snapcraft 创建快照
- javascript - 物化导航栏下拉菜单不起作用
- javascript - 使用数组数组创建多对一关系
- json - 如何在 ASP MVC 的 Json 文件中追加记录?
- javascript - CONTAINER(位于 GROUP 内)内的 Sprite 不可见
- r - 检查栅格是否翻转
- java - Apache POI 无法从 Excel 单元格中正确读取秒数