4

I have JSON array like:

var data = [
{
  "name": "Jim",
  "age" : 25
},
{
  "name": "Jerry",
  "age": 27
}
];

in HTML:

<ul>
  <li ng-repeat="val in data | filter:{age: age}:true">{{val.name}}</li>
</ul>

The above code is working fine as i want the output, but i don't want to use ng-repeat where it creates loop and then i filter.

is there any another way where i can directly select the DATA from array where age = age ??

2
  • You would still need to go through the array and find the matching ages, so the answer is no. If you really want to get users from age then you have to think about an alternative data structure.
    – link
    May 26, 2014 at 9:23
  • Filters can be used anywere in angular expressions (there is nothing ngRepeat-specific about them). But it is not clear what exactly you want.
    – gkalpak
    May 26, 2014 at 9:23

4 Answers 4

6

Filters can be used in any angular expression (there is nothing ngRepeat-specific about them).
(They can be even used in JavaScript.)

E.g. the following expression displays the data associated with the first user (limitTo:1) that has an age of 25 (filter:{age: 25}), formatted as JSON (json):

{{data | filter:{age: 25}:true | limitTo:1 | json}}

See, also, this short demo.

2
  • What if I only want the name from the data received? Sep 19, 2015 at 8:10
  • 5
    @shyamalparikh: You can use an expression like: {{ (data | filter:{age: 25}:true | limitTo:1)[0].name }}
    – gkalpak
    Sep 19, 2015 at 12:43
4

As mentioned by @link in comments, there is no way to pluck the object with the required age from the array without looping through it. However, you're right in thinking that using ng-repeat here is not appropriate if you only want to display a single object from the array, so ideally the required object should be stored in your controller.

One approach would be to use $filter in your controller instead:

$scope.obj_with_correct_age = $filter("filter")(data, {age: age});

<li>{{ obj_with_correct_age.name }}</li>
1

I realize this is an old thread but for completeness.

This works:

{{data.Systems[data.Detail.SystemId].System}}

This way, you don't need to filter the data.

0

If you want to parse single value of name. like {"name":"value"}. so after $http post, i am assuming that your response in var data= response.

Now find, like console.log(data[0].name); Here, result will be Jim

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.