Omar AMRANI
Omar AMRANI

Reputation: 507

AngularJS - Filter nested object in Javascript

I've a nested object as following:

[
  {
    "$id": "25",
    "Field": {
      "$id": "26",
      "Key": "bb3927b1-fcbb-4fc4-8eff-24b7a20fad7b",
      "EntityKey": "e904000c-b0b8-49ca-8a49-42a2e5b5d295",
      "PostalCode": "12345",
      "City": "My city1"
    },
    "EntityId": "MyEntity"
  },
  {
    "$id": "27",
    "Field": {
      "$id": "28",
      "Key": "ad4f2cb5-7397-474d-aed7-ff4bcc14d292",
      "EntityKey": "e904000c-b0b8-49ca-8a49-42a2e5b5d295",
      "PostalCode": "67890",
      "City": "My city2"
    },
    "EntityId": "MyEntity"
  }
]

In my HTML page, I'd like to filter by PostalCode or City:

<select ng-model="filterBy" ng-init="filterBy='EntityId'">
  <option value="EntityId">Entity</option>
  <option value="Field.PostalCode">PostalCode</option>
  <option value="Field.City">City</option>
</select>
<input type="text" ng-model="query[filterBy]" autofocus />

Using the function in JavaScript:

$filter('filter')(array, expression, comparator)

I can see only EntityId which is working, but not the others fields.

P.S: I know how to use it in HTML binding:

    | filter: {Field: {City: 'my-value'}} 

My intention is to do the same using the filter in JavaScript.

Thanks for your help.

Omar

Upvotes: 0

Views: 1424

Answers (2)

Boris
Boris

Reputation: 532

You can use $filter like this to match to all fields, deeply:

$filter('filter')($scope.unfilteredList, {$: '67890'});

Or use a function:

$filter('filter')($scope.unfilteredList, function(fullObject){
  // assuming $scope.filterBy contains the string `PostalCode`
  return fullObject.Field[$scope.filterBy] === '67890';
});

Upvotes: 1

o4ohel
o4ohel

Reputation: 1789

So, which part of what you've tried doesn't work? Here's a plnkr that demonstrates the filter both in html and js.

$scope.filteredList = $filter('filter')($scope.list, {
  Field: {Name: 'City'}
});

Upvotes: 1

Related Questions