Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find an object in a list based on attribute value in Angular JS

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"?

like image 704
kgautron Avatar asked Dec 04 '13 15:12

kgautron


2 Answers

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/

like image 138
Mathew Berg Avatar answered Nov 10 '22 11:11

Mathew Berg


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

like image 6
Isabeau Bergeron Avatar answered Nov 10 '22 13:11

Isabeau Bergeron