kga*_*ron 6 javascript angularjs
有没有一种简单的方法可以根据属性值在列表中查找对象,而无需在列表上循环?
例如,给出如下列表:
var lst = [
{
name: "foo",
value: "fooValue"
},
{
name: "bar",
value: "barValue"
}
];
Run Code Online (Sandbox Code Playgroud)
是否有某种" find"方法,这样lst.find("name", "foo")会返回具有" name"属性值为" foo"的对象?
Mat*_*erg 29
您可以使用$ filter服务:
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);
}
Run Code Online (Sandbox Code Playgroud)
jsFiddle:http://jsfiddle.net/W2Z86/
小智 5
如果你想进行严格的比较,你需要将比较器(第三个参数)设置为true,如下所示(基于Mathew的答案):
var newTemp = $filter("filter")(lst, {name:'foo'}, true);
Run Code Online (Sandbox Code Playgroud)
请参阅AngularJS网站上有关$ filter的文档:https://docs.angularjs.org/api/ng/filter/filter