Filtering multiple value with multiple key in json array using lodash

后端 未结 3 1284
一向
一向 2021-02-10 18:01

i have a dynamic data each time there could be dynamically different key value pair to be filtered in different data. how can we filter it with multiple key,value in lodash. i w

3条回答
  •  囚心锁ツ
    2021-02-10 18:57

    The _.filter function which iterates over elements of collection which is passes on first parameter in your case it's data and second parameter should be a function which is invoked per iteration for more info see Documentation.

    For this in your example you can use Arrow Functions

    Please find below snippet for more info.

    Change your filterby var as below

    var filterby = (m) => { return m => m.PARTY == "REPUBLICAN" || m.PARTY == "DEMOCRAT" && m.BALLOT_STATUS == "PERM" || m.BALLOT_STATUS == "POLL"  };
    

    var data = [ {
      "VOTER" : 1012,
      "PARTY" : "REPUBLICAN",
      "PRECINCT" : 2408,
      "AGE_GROUP" : "71 +",
      "LAST_VOTED" : "08/2006",
      "YEARS_REG" : 51,
      "BALLOT_STATUS" : "PERM"
    }, {
      "VOTER" : 1013,
      "PARTY" : "REPUBLICAN",
      "PRECINCT" : 2411,
      "AGE_GROUP" : "71 +",
      "LAST_VOTED" : "08/2006",
      "YEARS_REG" : 50,
      "BALLOT_STATUS" : "PERM"
    }, {
      "VOTER" : 1014,
      "PARTY" : "DEMOCRAT",
      "PRECINCT" : 2424,
      "AGE_GROUP" : "71 +",
      "LAST_VOTED" : "08/2006",
      "YEARS_REG" : 50,
      "BALLOT_STATUS" : "PERM"
    }, {
      "VOTER" : 1015,
      "PARTY" : "DEMOCRAT",
      "PRECINCT" : 2418,
      "AGE_GROUP" : "71 +",
      "LAST_VOTED" : "08/2006",
      "YEARS_REG" : 50,
      "BALLOT_STATUS" : "POLL"
        },{
      "VOTER" : 1109,
      "PARTY" : "AMERICAN INDEP",
      "PRECINCT" : 2404,
      "AGE_GROUP" : "71 +",
      "LAST_VOTED" : "08/2006",
      "YEARS_REG" : 34,
      "BALLOT_STATUS" : "POLL"
    },{
      "VOTER" : 1111,
      "PARTY" : "DECLINED",
      "PRECINCT" : 2414,
      "AGE_GROUP" : "71 +",
      "LAST_VOTED" : "08/2006",
      "YEARS_REG" : 34,
      "BALLOT_STATUS" : "POLL"
    }
    
    ]
    
    
    
    //var filterby = {"PARTY":["REPUBLICAN","DEMOCRAT"],"BALLOT_STATUS":["PERM","POLL"]}
    
    var filterby = (m) => { return m => m.PARTY == "REPUBLICAN" || m.PARTY == "DEMOCRAT" && m.BALLOT_STATUS == "PERM" || m.BALLOT_STATUS == "POLL"  };
    
    
    var filtered_data = _.filter(data, filterby);
    console.log(filtered_data);
    
    

提交回复
热议问题