JavaScript | AngularJS:按嵌套值过滤集合

时间:2016-07-01 21:09:14

标签: javascript angularjs collections filter nested

按数组

中的嵌套项过滤集合

说有一个集合:

[ { key: '', param: '', array: ['a', 'b', 'c'] },... ]

使用[Angular] $filter('filter') ,如何返回.array包含指定值'c'的对象集合?

例如,可以想象写下以下内容。

var token = 'c';
var query = { array: token };
var anyWithC = filter(collection, query, true);

这似乎没有用,所以我试过......

var query = { array: [token] };

我认为这也不起作用。

有人能让我直截了当吗?这有可能以这种方式过滤吗?我必须使用function而不是查询对象吗?

2 个答案:

答案 0 :(得分:0)

使用Underscore library's _.filter(list,predicate);

工作demo

var sample = [{
  name: 'test',
  lastName: 'test',
  address: ['a', 'b', 'c']
}, {
  name: 'test1',
  lastName: 'test1',
  address: ['d', 'e', 'f']
}, {
  name: 'test2',
  lastName: 'test2',
  address: ['g', 'h', 'i']
}];
//key is the objecy key from which the value will be extracted to compare with the token.
function filterByKey(list, key, token) {
  var filterArray = _.filter(list, function(value) {
    //If Undefined value then should return false
    if (_.isUndefined(value[key])) {
      return false;
    } else if (_.isArray(value[key])) {
      //Checks the extracted value is an Array
      return _.contains(value[key], token);
    }else {
        return value[key] === token;
    }
  });
  return filterArray;
}

console.log('Output ------------- ', filterByKey(sample, 'address', 'h'));

答案 1 :(得分:0)

你可以使用lodash https://lodash.com/docs

使用angular和lodash创建了一个JSFiddle: https://jsfiddle.net/41rvv8o8/

这是基于您提供的数据,此演示不区分大小写(大小写)。

HTML

<div ng-app="app">
  <example-directive>
  </example-directive>
</div>

的Javascript

var app = angular.module('app',[]);

app.directive('exampleDirective', function() {
    return {
    template:'<h1>Collections with array containing c</h1><ul><li ng-repeat="collection in matchcollections">key: {{collection.key}}, param: {{collection.param}}, <div ng-repeat="item in collection.array">{{item}}</div></li></ul>',
    controller: function($scope){

      $scope.collections = [ { key: 'A', param: 'A1', array: ['a', 'b', 'c'] },{ key: 'B', param: 'B1', array: ['x', 'h', 'c'] },{ key: 'C', param: 'C', array: ['t', 'a', 'k'] }];

      $scope.matchcollections = _.filter($scope.collections, function(c){
        return _.includes(c.array,'c')
      });
      console.log("Collection with match: ", $scope.matchcollections);
    }
  }
});

希望这有帮助!