user10691436
user10691436

Reputation:

How do i filter an array inside of a array of objects using filter?

I have an array of products and models that I'm using 'filter'

var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {

  $scope.products = [{
      'id': 1,
      'category': 'Tv',
      'models': [{
          'modelno': 12,
          'modelname': 'ASF456'

        },
        {
          'modelno': 13,
          'modelname': 'Aip456'

        }
      ]
    },

    {
      'id': 2,
      'category': 'Mobile',
      'models': [{
          'modelno': 21,
          'modelname': 'FGH74'

        },
        {
          'modelno': 22,
          'modelname': 'UIO06'

        }
      ]

    }

  ];

  $scope.search = '';
  $scope.filterData = function() {
    return $scope.products.filter(function(item) {

      return (item.id.toString().indexOf($scope.search) > -1

        ||
        (item.category.toLowerCase().indexOf($scope.search)) > -1)



    });

  }
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<body ng-app="myApp" ng-controller="myCtrl">
  <input type="text" ng-model="search">
  <h1 ng-repeat="x in filterData() | filter :search">{{x.id}} {{x.category}}</h1>
</body>

to filter these products by id and category. The filter is working but i want to add one more field inside filter modelname .

How do I set the filter to only apply to the id,category and modelname field of my array rather than every field?

How do I set the filter to only apply to the id,category and modelname field of my array rather than every field?

i want to filter by id category ,modelname

now these two fields id ,category filter is done but i want to add modelname also but modelname is inside models array here i am facing problem

Upvotes: 2

Views: 128

Answers (2)

FarukT
FarukT

Reputation: 1668

You can add another or condition like this

 || (item.models !== null && item.models.length > 0 && item.models.filter(e => {return e.modelname.search($scope.search) > 0 }).length > -1)

Upvotes: 1

BartoszTermena
BartoszTermena

Reputation: 1487

Do i understood correctly - you want to filter your $scope.products by means of id ? if so try like this:

<input ng-model="id " type="number" min="0"/>
<br />
<div ng-repeat="x in products | IDFiletr:id">
  {{x.category}}
  <br />
</div>

JS:

app.filter('IDFiletr',function(){
    return function(data, id) {
        if (!id) return data;
        var ids = [];
        angular.forEach(data, function(item){
            if(item.id === id) {
                ids.push(item);
            }
        });
        return ids;
    };
});

plunker: http://plnkr.co/edit/q9DsvZP4scA1oKsJj3Vu?p=preview

Upvotes: 0

Related Questions