How to filter a javascript object array with variable parameters

前端 未结 1 610
日久生厌
日久生厌 2020-12-05 05:38

I want to select the objects based on the properties of the objects, but not always the same properties. In other words:

arr = [
    { name: \"joe\",   age21         


        
相关标签:
1条回答
  • 2020-12-05 06:28

    Here's a functional approach that should work for any numbers of properties given the object:

    function filter(arr, criteria) {
      return arr.filter(function(obj) {
        return Object.keys(criteria).every(function(c) {
          return obj[c] == criteria[c];
        });
      });
    }
    

    For example:

    var arr = [
      { name: 'Steve', age: 18, color: 'red' },
      { name: 'Louis', age: 21, color: 'blue' }, //*
      { name: 'Mike', age: 20, color: 'green' },
      { name: 'Greg', age: 21, color: 'blue' }, //*
      { name: 'Josh', age: 18, color: 'red' }
    ];
    
    console.log(filter(arr, { age: 21, color: 'blue' }));
    //^ {age:21, color:'blue', name:'Louis}
    //  {age:21, color:'blue', name:'Greg'}
    

    Not sure about your performance issue, but this should be OK.

    Edit: You could make this more powerful with regular expressions, something like this:

    function filter(arr, criteria) {
      return arr.filter(function(obj) {
        return Object.keys(criteria).every(function(c) {
          return new RegExp(criteria[c]).test(obj[c]);
        });
      });
    }
    
    console.log(filter(arr, { age: /^2\d$/, color: /^(red|blue)$/ }));
    //^ Louis, Greg                --^-- twenty-something
    //                                               ----^---- red OR blue
    
    0 讨论(0)
提交回复
热议问题