3 回答
TA贡献1798条经验 获得超3个赞
你可以你filter的数组
const items = [
{code: "1", fruits: "APPLE", color: "red"},
{code: "2", fruits: "BANANA", color: "dummy"},
{code: "3", fruits: "BANANA", color: "anotherDummy"},
{code: "4", fruits: "ORANGE", color: "orange"}
];
const keyword = 'BANANA';
const filter = items.filter(item => (item.code === keyword || item.fruits === keyword ||item.color === keyword));
console.log(filter);
也适用于多个过滤器/搜索
const items = [
{code: "1", fruits: "APPLE", color: "red"},
{code: "2", fruits: "BANANA", color: "dummy"},
{code: "3", fruits: "BANANA", color: "anotherDummy"},
{code: "4", fruits: "ORANGE", color: "orange"}
];
const keyword = ['APPLE', 'BANANA'];
const filter = items.filter(item => (
keyword.includes(item.code)
|| keyword.includes(item.fruits)
|| keyword.includes(item.color)
));
console.log(filter);
TA贡献1936条经验 获得超6个赞
希望这可以帮助 -
此代码将返回包含找到的项目的数组
这将比较每个项目的所有属性/键给出的值。
此外,最好创建自定义(创建 findCustom() 函数)而不是覆盖内置的 find() 方法。
var items = [{code: "1", fruits: "APPLE", color: "red"},
{code: "2", fruits: "BANANA", color: "dummy"},
{code: "3", fruits: "BANANA", color: "anotherDummy"},
{code: "4", fruits: "ORANGE", color: "orange"}]
items.findCustom = (value) =>{
let results = [];
items.find((item) => {
var listKeys = Object.keys(item);
listKeys.forEach((keyName) => {
if(item[keyName] == value)
results.push(item);
})
})
return results;
}
console.log(items.findCustom("BANANA"))
TA贡献1946条经验 获得超4个赞
你可以使用filter方法
let filteredArray = items.filter(item => item.fruits ==='BANANA');
console.log(filteredArray);
更新
对于更多动态过滤器,您可以创建要查找的字符串列表让我们说:
let fruitsToFilter = ['BANANA', 'APPLE',...]
然后就可以使用像这样的过滤方法来实现动态过滤
let filteredArray = items.filter(item => fruitsToFilter.includes(item.fruits));
console.log(filteredArray);
添加回答
举报