如何在嵌套的Json中使用angularjs进行过滤

问题描述 投票:2回答:1

我需要在嵌套的JSON数组中进行查询,如下所示。我想检查名字是否是约翰,如果爱好有运动,但它不起作用。

以下代码的结果如下:

[
  {"id":1,"name":"John","hobbies":[{"kind":"sport"},{"kind":"music"}]},
  {"id":5,"name":"John","hobbies":[{"kind":"swimming"},{"kind":"opera"}]}
] 

但它必须是{"id":1,"name":"John","hobbies":[{"kind":"sport"}{"kind":"music"}]}

function MyCtrl($scope, $filter) {
    $scope.items = [
        {id:1, name:'John',hobbies:[{kind:"sport"},{kind:"music"}]},
        {id:2, name:'Steve',hobbies:[{kind:"opera"},{kind:"theatre"}]},
        {id:3, name:'Joey'},
        {id:4, name:'Mary'},
        {id:5, name:'John',hobbies:[{kind:"swimming"},{kind:"opera"}]}];
    $scope.filteredData = $filter('filter')($scope.items, {name:'John',hobbies:[{kind:''}]});
    $scope.json=JSON.stringify($scope.filteredData);
    // $scope.json2=JSON.stringify($scope.y);
};
javascript angularjs json search filter
1个回答
1
投票

版本1.3.8支持这种过滤器

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>
  <script>
    (function() {

      angular.module("myapp", []).controller('MainCtrl', ['$scope', '$filter', function($scope, $filter) {

            $scope.items = [
              {id:1, name:'John',hobbies:[{kind:"spor"},{kind:"music"}]},
              {id:2, name:'Steve',hobbies:[{kind:"opera"},{kind:"theatre"}]},
              {id:3, name:'Joey'},
              {id:4, name:'Mary'},
              {id:5, name:'John',hobbies:[{kind:"swimming"},{kind:"opera"}]}
            ];    
            
            $scope.filteredData = $filter('filter')($scope.items, 
              { name: 'John', hobbies: [ {kind: 'swimming'}]}
            );

      }]);
    }());
  </script>
  <style></style>
</head>

<body ng-app="myapp" ng-controller="MainCtrl">

    {{filteredData}}

</body>

</html>
© www.soinside.com 2019 - 2024. All rights reserved.