var mainobj=[[{
"title": "Nifty News: Dapper Labs pursuing DAOs, Bundesliga partners with Sorare, and more. ",
"category": [
"Dapper Labs",
" Brud",
" Sorare",
" Bundesliga",
" Etched",
" Hockey Diversity Alliance",
" Archdiocese of Bangkok NFT"
],
"description": "Nifty News: Dapper Labs pursuing DAOs, Bundesliga partners with Sorare, and more. ",
},
{
"title": "Bitcoin returns to $1T asset as BTC price blasts to $55K",
"category": [
"Bitcoin",
" BTC price"
],
"description": "Bitcoin returns to $1T asset as BTC price blasts to $55K",
}]]
var categoryfilterArray=['Bitcoin','Bundesliga','Sorare']
我需要过滤器匹配mainobj中的categoryfilterArray
首先,我假设您实际上没有一个数组包含另一个数组,而是一个对象数组,如:
const mainobj = [
{
title: "Nifty News: Dapper Labs pursuing DAOs, Bundesliga partners with Sorare, and more. ",
category: [
"Dapper Labs",
"Brud",
"Sorare",
"Bundesliga",
"Etched",
"Hockey Diversity Alliance",
"Archdiocese of Bangkok NFT"
],
description: "Nifty News: Dapper Labs pursuing DAOs, Bundesliga partners with Sorare, and more. ",
},
{
title: "Bitcoin returns to $1T asset as BTC price blasts to $55K",
category: [
"Bitcoin",
"BTC price"
],
description: "Bitcoin returns to $1T asset as BTC price blasts to $55K",
}
];
从那里,您可以使用如下函数查看category
数组和categoryfilterArray
的交集:
const arrayIntersection = (array1, array2) => {
return array1.filter(x => array2.includes(x));
};
然后就看你如何比较交集了。
如果您试图找到categories
包含所有categoryfilterArray
值的对象,您可以将相交数组作为字符串进行比较:
const matchingObj = mainobj.filter(obj => {
return JSON.stringify(arrayIntersection(obj.category, categoryfilterArray)) === JSON.stringify(categoryfilterArray);
});
如果您只在交集中寻找一个或多个目标类别,您可以使用布尔转换:
const matchingObj = mainobj.filter(obj => {
return Boolean(arrayIntersection(obj.category, categoryfilterArray).length);
});
任何大于0
的交集长度将返回true
,并返回过滤器中的对象。或者,您可以检查arrayIntersection(obj.category, categoryfilterArray).length > 0
。
示例:https://stackblitz.com/edit/angular-ivy-hew9bq?file=src/app/app.component.ts