具有多个参数或关键字的JavaScript Filter()函数

时间:2019-12-25 04:52:54

标签: javascript

我有一个产品列表的对象,并且我创建了一个数组以应用过滤器功能以从该数组获取参数。像下面一样

var selectedProducts = ['music', 'dance']
var products = [
    {
        ID : 1,
        name : "pro1",
        category : "music"
    },
    {
        ID : 2,
        name : "pro2",
        category : "yoga"
    },
    {
        ID : 3,
        name : "pro3",
        category : "music"
    },
    {
        ID : 4,
        name : "pro4",
        category : "dance"
    },
]

function filterFunction(){
    return products.filter((abc) => {
        selectedProducts.forEach(function(item, index){
            return abc.category == selectedProducts[index]
        });
    });
}

我想做的是当用户选中任何复选框时,选定的值将存储在selectedProducts []数组中,然后在这些值上调用filter函数,并将数组作为参数通过forEach方法传递。代码在循环的每次迭代中都可以正常工作,但是最后它返回了一个空的对象数组。我的代码有什么问题吗?

2 个答案:

答案 0 :(得分:4)

true循环的回调函数返回forEach()不会对过滤条件产生任何影响。

这是使用Array.prototype.includes()的另一种方法:

products.filter(({category}) => selectedProducts.includes(category));

完整摘要:

const selectedProducts = ['music', 'dance']
const products = [
    {
        ID : 1,
        name : "pro1",
        category : "music"
    },
    {
        ID : 2,
        name : "pro2",
        category : "yoga"
    },
    {
        ID : 3,
        name : "pro3",
        category : "music"
    },
    {
        ID : 4,
        name : "pro4",
        category : "dance"
    },
]

function filterFunction(){
    return products.filter(({category}) => selectedProducts.includes(category));
}

console.log(filterFunction());

答案 1 :(得分:-1)

使用filtersome的组合:

function filterFunction(){
    return products.filter((abc) => {
        return selectedProducts.some(function(category){
            return abc.category === category;
        });
    });
}

some()函数如果true中的至少一个与selectedProducts中的category相匹配,则返回abc

我们也可以使用includes

function filterFunction(){
    return products.filter((abc) => {
        return selectedProducts.includes(abc.category);
    });
}

在开发前端Web时,我更喜欢使用filtersome的组合,因为这些功能的支持范围比includes宽(使用更多浏览器版本)。

参考:

Array.prototype.filter

Array.prototype.some

Array.prototype.includes

相关问题