Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

Is there a simple way to find an object in a list based on an attribute value, without looping on the list?

For example given a list like the following :

var lst = [{name : "foo", value : "fooValue"}, {name: "bar", value: "barValue"}];

is there some kind of "find" method, such that lst.find("name", "foo") would return the object which has a "name" attribute with the value "foo"?

share|improve this question
2  
At most, the loop would be hidden from you, but still execute inside some other function. If that is acceptable you can use the filterFilter service. – Yoshi Dec 4 '13 at 15:22
    
I know a loop has to be done somehow, I'm just searching for a lighter syntax. – KayKay Dec 4 '13 at 16:06
up vote 7 down vote accepted

You can use the $filter service:

angular.module('app', [])

function ParentCtrl($scope, $filter){
    var lst = [{name : "foo", value : "fooValue"}, {name: "bar", value: "barValue"}, { name: 'foo', value: 'something else'}];
    var newTemp = $filter("filter")(lst, {name:'foo'});
    console.log(newTemp);
}

jsFiddle: http://jsfiddle.net/W2Z86/

share|improve this answer
    
Thanks that's what i was looking for. – KayKay Dec 4 '13 at 16:12
    
Thanks @matthew-berg . For other noobs (like me). In case it's not immediately obvious, newTemp is an array of objects that match the filter. If you know you've got a single object that matches, you might want the first element in the array (i.e. newTemp[0] ). – James Jun 8 '15 at 10:17

If you want a strict comparison, you need to set the comparator (3rd argument) to true like the following (based on Mathew's answer):

var newTemp = $filter("filter")(lst, {name:'foo'}, true);

See the doc on $filter on AngularJS site: https://docs.angularjs.org/api/ng/filter/filter

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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