0

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

2 Answers 2

1

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'}
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your swift answer o4ohel! In fact, how can I pass to my JS function dynamically the object: Field: {Name: 'City'} From a select/option for example: <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 />
@OmarAMRANI : I've updated the plnkr with 2 caveats: * I don't know if that's what you were looking for. * Without understanding your full intent, it seems like an overly complex solution.
I'm note sure if the Plunker is updated. I'm getting always the same version.. Could you pls send me the new link? Thanks!
1

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';
});

1 Comment

Thanks Boris, that helps as well!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.