[英]Trouble filtering an array of objects based on a nested array
我有一組看起來像這樣的對象:
const nodes = [{
post: 'a',
categories: [{title:'Events'}, {title: 'Announcements'}]
},
{
post: 'b',
categories: [ {title:'Events'}]
},
{
post: 'c',
categories: [ {title:'Announcements'}]
},
]
我需要像這樣根據 arrays 過濾它們:
const sectionCategory1 = ['Events', 'Announcements']
const sectionCategory2 = ['Events']
這樣只有包含 sectionCategory 條目的帖子才會保留。 例如,如果我使用 sectionCategory2 過濾器返回帖子 a 和 b。
我嘗試了以下方法:
const categoryNodes = nodes.filter((node => sectionCategory2.includes( node.categories.map(n => n.title))))
和
const categoryNodes = nodes.filter((node => sectionCategory2.includes( node.categories)))
也沒有用。 我敢肯定,我在這里缺少一些基本的東西,而且我知道以前也有人問過類似的問題,但是我已經嘗試了其他解決方案,並且一直在反對這一點。
在特定節點的迭代中,您有 2 個 arrays 可以相互檢查:要包含的類別,例如['Events']
,以及節點的類別標題,例如['Events', 'Announcements']
。 因此,您將需要一個嵌套循環,而不僅僅是一個.includes
:遍歷一個數組的每個元素以查看是否有任何匹配另一個數組中的元素。
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.