Cody
Cody

Reputation: 10015

JavaScript | AngularJS: Filter Collection by Nested Value

Filter Collection by Nested Item in Array

Say there's a collection:

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

Using [Angular] $filter('filter'), how can I return a collection of objects whose .array contains the specified value 'c'?

For instance, one could imagine writing the following.

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

This doesn't seem to work so I've tried...

var query = { array: [token] };

I don't think this is working either.

Could someone set me straight on this one? Is this possible to filter this way? Must I use a function instead of a query object?

Upvotes: 0

Views: 157

Answers (2)

CronbachAlpha
CronbachAlpha

Reputation: 355

You can use lodash https://lodash.com/docs

Have created a JSFiddle using angular and lodash: https://jsfiddle.net/41rvv8o8/

This is based on the data you provided, and this demo is not case sensitive (upper and lower cases).

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);
    }
  }
});

Hope this helps!

Upvotes: 0

Vipul Panth
Vipul Panth

Reputation: 5801

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

Working 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'));

Upvotes: 0

Related Questions