ArchDeveloper
ArchDeveloper

Reputation: 23

How to filter with angularjs in nested Json

I need a query in nested a JSON array like following. I want to check if name is John and if hobbies have sport but it didn't work.

The result of following code like that:

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

but it must be {"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);
};

Upvotes: 2

Views: 46

Answers (1)

Nishanth
Nishanth

Reputation: 835

This kind of filter is supported in version 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>

Upvotes: 1

Related Questions