JVG
JVG

Reputation: 21150

AngularJS / Javascript: Find a string match in a nested object

I have a complex object (a user object) that has nested arrays and nested objects within it.

I have a search filter that is relatively complicated as well (checkboxes determining which items are returned, along with a search input).

Currently I search in an object like so:

for(var key in item){
  if(item[key] && item[key].length && String(item[key]).toLowerCase().indexOf($rootScope.filt.searchFilter.toLowerCase()) !== -1){
    realSave = true; 
  }
}

However, this only works for the first layer of objects within an item; I need to also search for objects within objects.

How can i do this? Is this a simpler way than the above? (Note, I can't just use ng-repeat="item in items | searchFilter" as this needs to also parse checkboxes and return values accordingly.

Upvotes: 0

Views: 104

Answers (2)

Petr Averyanov
Petr Averyanov

Reputation: 9476

You can use angular filter like this:

app.controller('MainCtrl', function($scope, $filter) {
  $scope.a = [{name : 'pit'}, {name : {a : 'pit'}}, {name : { a : { b : 'pit'}}}];
  $scope.find = $filter('filter')($scope.a, 'pit');
});

http://plnkr.co/edit/TenLILkXJ0zwqMVtAj35?p=preview

Upvotes: 0

Jeremy Thille
Jeremy Thille

Reputation: 26360

Try

realSave = (JSON.stringify(item).indexOf($rootScope.filt.searchFilter.toLowerCase()) !== -1)

(It's a long line, scroll to the right)

It will transform your whole object into a single string, then you can search for the sub-string you're looking for anywhere inside it.

Upvotes: 1

Related Questions