首页 > 解决方案 > 如何通过另一个对象值的参数过滤特定对象值

问题描述

这是输入。在“帖子”属性中,我拥有所有帖子。我需要通过“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))

什么是最好的选择?

标签: javascriptobjectecmascript-6

解决方案


您要过滤的数组是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);


推荐阅读