我有一个对象数组,如果我的过滤器数组与键的字符串匹配,我希望过滤掉那些对象。
// my stores
var stores = [
{
id: 1,
store: 'Store 1',
storeSells: "Belts|Handbags|Watches|Wallets"
},
{
id: 2,
store: 'Store 2',
storeSells: "Handbags|Personal Accessories|Jewelry|Eyewear|"
},
{
id: 3,
store: 'Store 3',
storeSells: "Belts|Travel|Charms|Footwear|"
},
{
id: 4,
store: 'Store 3',
storeSells: "Charms|Footwear|"
}
]
// my filters
var filters = ["Handbags","Belts"]
因此,如果我的filters
数组具有handbags
和belts
。我只希望过滤ID为1,2 and 3
的商店,因为它们包含这些关键字。你能帮我吗?
答案 0 :(得分:2)
您可以尝试使用Array.prototype.filter()
filter()
方法将创建一个新数组,其中包含所有通过提供的功能实现的测试的元素。
some()
方法测试数组中的至少一个元素是否通过了由提供的函数实现的测试。它返回一个布尔值。
includes()
方法确定是否可以在另一个字符串中找到一个字符串,并根据需要返回true或false。
// my stores
var stores = [
{
id: 1,
store: 'Store 1',
storeSells: "Belts|Handbags|Watches|Wallets"
},
{
id: 2,
store: 'Store 2',
storeSells: "Handbags|Personal Accessories|Jewelry|Eyewear|"
},
{
id: 3,
store: 'Store 3',
storeSells: "Belts|Travel|Charms|Footwear|"
},
{
id: 4,
store: 'Store 3',
storeSells: "Charms|Footwear|"
}
]
// my filters
var filters = ["Handbags","Belts"];
var res = stores.filter(item => filters.some(i=>item.storeSells.includes(i)));
console.log(res);