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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在嵌套的Json中使用angularjs进行过滤相关的知识,希望对你有一定的参考价值。

我需要在嵌套的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);
};
答案

版本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>

以上是关于如何在嵌套的Json中使用angularjs进行过滤的主要内容,如果未能解决你的问题,请参考以下文章

如何在AngularJS中使用ng-repeat创建嵌套结构[关闭]

我如何在 angularjs 中显示子嵌套评论

如何在angularjs中通过ajax显示来自url的json数组

json #AngularJS,#JavaScript:使用ng-repeat循环遍历嵌套数组

如何在 Laravel 5 中处理嵌套的 JSON 对象请求?

在 Python 中通过嵌套的 Json/dict 解析