最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Find an object in a list based on attribute value in Angular JS - Stack Overflow

programmeradmin1浏览0评论

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

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 edited Mar 2, 2017 at 14:26 Pieter VDE 2,2354 gold badges26 silver badges45 bronze badges asked Dec 4, 2013 at 15:17 kgautronkgautron 8,26310 gold badges41 silver badges60 bronze badges 2
  • 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 Commented Dec 4, 2013 at 15:22
  • I know a loop has to be done somehow, I'm just searching for a lighter syntax. – kgautron Commented Dec 4, 2013 at 16:06
Add a comment  | 

2 Answers 2

Reset to default 30

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/

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

发布评论

评论列表(0)

  1. 暂无评论