繁体   English   中英

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

[英]Filter objects in array in array

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

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来尝试与键匹配,但这对我不起作用。

首先,我需要映射到帖子以到达标签并映射到它们,然后我需要在具有键的数组上进行映射以使其与标签数组中的键相匹配,并返回包含匹配标签的帖子。

像这样

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 )
     )
   )

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

 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; } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM