Filter array of objects with another array of objects

前端 未结 9 1786
小蘑菇
小蘑菇 2020-11-27 05:18

This question is similar to this one Jquery filter array of object with loop but this time I need to do the filter with an array of objects.

Exemple:

I have

9条回答
  •  醉话见心
    2020-11-27 06:04

    This code will match with not only by userid and projectid but with all properties of myFilter[j].

    var filtered = myArray.filter(function(i){
        return myFilter.some(function(j){
            return !Object.keys(j).some(function(prop){
                return i[prop] != j[prop];
            });
        });
    });
    
    console.log(filtered);
    

    So you can use

    myFilter = [
        {
            projectid: "11"
        },
        {
            userid: "101"
        },
        {
            userid: "103",
            projectid: "13",
            rowid: "3"
        }
    ];
    

    Will return

    [ { userid: '101', projectid: '11', rowid: '1' },
    { userid: '103', projectid: '13', rowid: '3' },
    { userid: '101', projectid: '10', rowid: '4' } ]
    

    Wich means all elements with

    (projectid=="11") 
    OR (userid=="101") 
    OR ( (userid=="103") AND (projectid=="13") AND (rowid=="3") )
    

提交回复
热议问题