从对象数组中选择属性select的常用功能

时间:2017-11-22 18:20:18

标签: javascript angularjs

我有四个不同属性从数组中选择的函数。

if ($scope.filters.filter1)
    $scope.filteredEntries = $scope.filteredEntries.filter(function (o)
    {
       return o.field1 === $scope.filters.filter1
    });

if ($scope.filters.filter2)
    $scope.filteredEntries = $scope.filteredEntries.filter(function (o)
    {
       return o.field2 === $scope.filters.filter2
    });

此代码是可重复的,但这并不好。我想把select放在单独的函数中。但选择条件在所有情况下都不同。我可以使用条件作为参数吗?我怎么能这样做?

我想在这个伪代码中做一些事情:

expression = e => e.field == value;
miniFilter(expression);
...
function miniFilter(expression)
{
   $scope.filteredEntries = $scope.filteredEntries.filter(function (expression)
   {
      return expression;
   });
 }

希望我的意图很明确。我不太熟悉js的方法论,所以请原谅我。

1 个答案:

答案 0 :(得分:1)

最初呈现重复代码的解决方案:



var data = [
  {field1: 'Tom', field2: 30}, 
  {field1: 'Max', field2: 30}, 
  {field1: 'Max', field2: 30}
];
var $scope = { filters: {
    filter1: 'Max',
    filter2: 30
  }
};

function MiniFilter(input, filters) {
  for (var prop in filters) {
    var filVal = filters[prop];
    if (filVal)
      input = input.filter(function(item) {        
        return item['field' + prop.match(/\d+$/)[0]] == filVal;
      });
  }
  return input;
}

var result = MiniFilter(data, $scope.filters);
console.log(JSON.stringify(result))




解决方案通过"表达式"



var data = [
  {field1: 'Tom', field2: 30}, 
  {field1: 'Max', field2: 30}, 
  {field1: 'Max', field2: 30}
];
var $scope = {filters: [
  function(x){ return x.field1 == 'Max';},
  function(x){ return x.field2 == 30;}
]};

function MiniFilter(input, expressions){
  for(var exp of expressions)
    input = input.filter(exp);
  return input
}

var result = MiniFilter(data, $scope.filters);
console.log(JSON.stringify(result));