简体   繁体   中英

How do you filter a json list by key-value in AngularJS?

I'm quite a beginner to AngularJS. Now I'm trying to list out a json file using ng-repeat . These are what I have:

filename.json:

{
  "name"    : "name data",
  "id"      : "id data",
  "country" : "country data",
  "age"     : "age data",
  "job"     : "job data"
}

The list is much longer than this one, but I could print everything into a table successfully by ng-repeat but without any filter. Now, I'm trying to take some items out. In the example, I might want to show without "id" and "age". Is there any suggestion to make a filter for this situation?

The following is what I've tried after looking up on several answers on Stack Overflow but failed. The answers are great but their situations don't really fit mine.

template:

<table>
  <tr ng-repeat="(key, data) in $ctrl.person | filter: $ctrl.toShow">
    <td>{{key}}</td>
    <td>{{data}}</td>
  </tr>
</table>

controller function:

function myCtrl ($http) {
  self = this; 
  self.toShow = function myFilter (key, value) {
    if (key == 'id' || key == 'age') {
      return false;
    } else {
      return true;
    }
  };
  $http.get('filename.json').then(function (response) {
    self.person = response.data;
  });
}
 app.filter('toShow', function () {
     return function (input) {
         return JSON.parse(input, ['field1', 'field2']);
     });
 });

The code above is based on fact that JSON.parse() can have second argument being an array of JSON field to grab. Here you put fields to show rather than to hide.

You can use ng-repeat with ng-show to filter fields you want to hide as below

<table>
    <tr ng-repeat="(key, data) in $ctrl.person" ng-show="key != 'id' && key != 'age'">
        <td>{{key}}</td>
        <td>{{data}}</td>
    </tr>
</table>

Working fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM