Search code examples
javascriptarraysfilterlodash

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.

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.


Solution

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