在数组中过滤数组中的对象

时间:2018-05-06 08:31:01

标签: javascript arrays filter lodash

我在所选标签的数组中有一个对象数组

const posts = 
[{note: 'something..', title: 'something..',
tags: [{title: 'First tag', key: '123'}, {title: 'Second tag', key: 'ABC'}]}, 
{note: 'another post..', title: 'another post..', 
tags: [{title: 'third tag', key: '098'}, {title: 'forth tag', key: 'ZYX'}, {title: 'fifth tag', key: '1A9'}]}]

我有一个带键的数组

const keys = ['123', 'ABC', '098', 'ZYX', '1A9']

我想返回已过滤的帖子。所以我尝试在这些帖子上.map.filter尝试与键匹配,但它对我不起作用。

首先,我需要映射帖子以获取标签并映射这些标签,然后我需要使用键将数组映射到与标签数组中的键匹配,并返回包含匹配标签的帖子

2 个答案:

答案 0 :(得分:0)

像这样的东西

const posts = [{note: 'something..', title: 'something..', tags: [{title: 'First tag', key: '123'}, {title: 'Second tag', key: 'ABC'}]}, {note: 'another post..', title: 'another post..', tags: [{title: 'third tag', key: '098'}, {title: 'forth tag', key: 'ZYX'}, {title: 'fifth tag', key: '1A9'}]}]


const keys = ['123', 'ABC', '098', 'ZYX', '1A9']

const filtered = posts.filter(post =>
   post.tags.some( tag => 
      keys.includes( tag.key )
     )
   )

答案 1 :(得分:0)

您可以通过使用键检查标记进行过滤。

var posts = [{ note: 'something..', title: 'something..', tags: [{ title: 'First tag', key: '123' }, { title: 'Second tag', key: 'ABC' }] }, { note: 'another post..', title: 'another post..', tags: [{ title: 'third tag', key: '098' }, { title: 'forth tag', key: 'ZYX' }, { title: 'fifth tag', key: '1A9' }] }],
    keys = ['123'], //, 'ABC', '098', 'ZYX', '1A9'],
    result = posts.filter(({ tags }) => tags.some(({ key }) => keys.includes(key)));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }