简体   繁体   English

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

[英]Filter objects in array in array

I have an array of objects within arrays from selected tags 我在选定标签的数组中有一个对象数组

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'}]}]

And I have an array with keys 我有一个带键的数组

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

I want to return the filtered posts. 我想退回已过滤的帖子。 So I tried to .map and .filter over these posts to try to match with the keys, but it doesn't work for me. 因此,我尝试在这些帖子上使用.map.filter来尝试与键匹配,但这对我不起作用。

First I need to map over posts to get to the tags and map over these and then I need to map over the array with keys to match them with the keys in the array of tags and return the post that contains the matched tag. 首先,我需要映射到帖子以到达标签并映射到它们,然后我需要在具有键的数组上进行映射以使其与标签数组中的键相匹配,并返回包含匹配标签的帖子。

Something like this 像这样

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

You could filter by checking the tags with the keys. 您可以通过使用键检查标签来进行过滤。

 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