0

If I have an object with a property that is an array, how can I filter by the first element of this property?

Data

{
    Id: "0",
    Name: ["John", "Doe"]
}

ngRepeat

<li ng-repeat="u in users | filter:{Name[0]: 'John'}">{{ u.Name[0] + ' ' + u.Name[1] }}</li>
3
  • 1
    You probably need a custom filter to achieve this. custom filter Commented Apr 18, 2016 at 11:34
  • This has an answer in here Commented Apr 18, 2016 at 11:55
  • thank you nubinub :D i think i've found the solution, but i will wait to see if there are any hacks that doesn't require custom filter Commented Apr 18, 2016 at 12:50

2 Answers 2

1

Slightly modified from this SO answer to work with arrays:

<li ng-repeat="u in users | filter: {Name: ['John']}">{{ u.Name[0] + ' ' + u.Name[1] }}</li>

Update: This doesn't seem to work after version 1.2.1 or so. You can see the difference in this fiddle using v1.2.1 and this one using v1.4.8. Not sure what's changed between these two or if the feature was ever even officially supported. As an alternative, you could use a function predicate, like so:

<li ng-repeat="u in users | filter: isJohn">{{ u.Name[0] + ' ' + u.Name[1] }}</li>

controller:

$scope.isJohn = function(value){
    return value.Name[0] === 'John';
};

But then again, that's not much simpler than creating a custom filter like nubinub suggested in the comments, and definitely less reusable.

Sign up to request clarification or add additional context in comments.

5 Comments

this doesnt work, it will works if i have 2 property FirstName and LastName, then i can filter like that SO answer, but i have an array-property
Did you try the modified version I wrote?
@nmtuan The code snippet in this answer should work on your array just fine
I tried your code on jsfiddle but it doesnt work, also tested on my own project jsfiddle.net/tzbgvzm2/1
@nmtuan Ah, you're right. I seem to have used an old version of angular when testing the original answer. My bad. I've updated the answer.
0

Try this

<li ng-repeat="u in users | filter:u.Name[0] == 'John'">{{ u.Name[0] + ' ' + u.Name[1] }}</li>

2 Comments

hmm how do i expect that u.Name[0] equals something ?
i want to filter out all the users that have his/her first-name (e.g Name[0]) equals 'John', with your expression i dont know where to put the filter-key 'John'

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.