我有一个对象数组,如果我的过滤器数组与键的字符串匹配,我希望过滤掉这些对象。
// 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 和 3
的商店,因为它们包含这些关键字。你能帮我解决这个问题吗?
最佳答案
The
filter()
method creates a new array with all elements that pass the test implemented by the provided function.
The
some()
method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
The
includes()
method determines whether one string may be found within another string, returning true or false as appropriate.
// 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);
关于javascript - 检查我的字符串是否包含数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58742025/