简体   繁体   中英

Trouble filtering an array of objects based on a nested array

I've got an array of objects that looks like this:

const nodes = [{
     post: 'a',
     categories: [{title:'Events'}, {title: 'Announcements'}]
     },
     {
     post: 'b',
     categories: [ {title:'Events'}]
     },
     {
     post: 'c',
     categories: [ {title:'Announcements'}]
     },
]

and I need to filter them based on arrays like this:

const sectionCategory1 = ['Events', 'Announcements']
const sectionCategory2 = ['Events']

so that only the posts that include the sectionCategory entries will remain. For instance if I use sectionCategory2 the filter returns posts a and b.

I've tried the following:

const categoryNodes = nodes.filter((node => sectionCategory2.includes( node.categories.map(n => n.title))))

and

const categoryNodes = nodes.filter((node => sectionCategory2.includes( node.categories)))

didn't work either. I'm sure there's something fundamental that I'm missing here and I know similar questions have been asked before but I've tried the other solutions and just keep beating my head against this.

Inside the iteration of a particular node, you have 2 arrays to check against each other: the categories to include, eg ['Events'] , and the category titles of the node, eg ['Events', 'Announcements'] . So, you'll need a nested loop, not just a single .includes : iterate over every element of one array to see if any matches an element in the other array.

 const nodes = [{ post: 'a', categories: [{title:'Events'}, {title: 'Announcements'}] }, { post: 'b', categories: [ {title:'Events'}] }, { post: 'c', categories: [ {title:'Announcements'}] }, ] const sectionCategory2 = ['Events'] const categoryNodes = nodes.filter( node => node.categories.map(n => n.title).some(title => sectionCategory2.includes(title) ) ); console.log(categoryNodes);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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