gpt4 book ai didi

javascript - 检查我的字符串是否包含数组中的元素

转载 作者:行者123 更新时间:2023-11-30 13:48:41 25 4
gpt4 key购买 nike

我有一个对象数组,如果我的过滤器数组与键的字符串匹配,我希望过滤掉这些对象。

// 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 数组有 handbagsbelts。我希望过滤 ID 为 1,2 和 3 的商店,因为它们包含这些关键字。你能帮我解决这个问题吗?

最佳答案

你可以试试Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Array.prototype.some()

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.

String.prototype.includes()

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com