link64
link64

Reputation: 1976

Is it possible to filter on object property names in AngularJS?

For the sake of argument, take the following (rather convoluted) JSON data structure and assume that I cannot change it:

 $scope.myObj = {
    "DynamicKeyName": {...},
    "AnotherKeyName": {...} 
    };

The values of the properties themselves are not important. Is it possible to filter this object based on the property names? For example, I just want to display the properties that meet a certain naming convention. Please note that I do not know the key names and don't want to hardcode them in to the application

Something along the lines of:

<div ng-repeat="(key,val) in myObj | filterByKey:'something'"></div>

I believe I might need to write a filter but the filters seem to be geared towards working with arrays.

Upvotes: 1

Views: 28

Answers (1)

Khanh TO
Khanh TO

Reputation: 48972

I don't know if there is an already built-in filter, but you could always write your own filters. Something like this:

app.filter("filterByKey",function(){
  return function (input,filter){
    var result = {};

    for (var key in input){
      if (key.indexOf(filter)>=0){
        result[key] = input[key];
      }
    }

    return result;
  }
});

DEMO

Upvotes: 1

Related Questions