[英]How to filter object attributes with AngularJS
I have a array of categories object 我有一个类别对象数组
categoriesTree : [
{name: 'cat1', id:1, selected : true},
{name: 'cat2', id:2, selected : false},
{name: 'cat3', id:3, selected : true},
{name: 'cat4', id:4, selected : false},
{name: 'cat6', id:6, selected : true},
]
To get the selected categories I did: 为了获得所选的类别,我做了:
selectedCategories = filterFilter($scope.categoriesTree, {selected:true})
this will give me: 这会给我:
categoriesTree : [
{name: 'cat1', id:1, selected : true},
{name: 'cat3', id:3, selected : true},
{name: 'cat6', id:6, selected : true},
]
But to reduce the POST data to send, I just want the id attribue so I want an array like this: 但是为了减少POST数据的发送,我只想要id属性,所以我想要一个这样的数组:
['1', '3', '6']
Is that possible to do with AngularJS filters ? 这可能与AngularJS过滤器有关吗?
You can create your own custom angularjs filter that not only "filters" but also "projects" your set into a different set. 您可以创建自己的自定义angularjs过滤器,该过滤器不仅可以“过滤”,还可以将您的集合“投影”到其他集合中。 I think you can definitely project each category object into just its ID. 我认为您绝对可以将每个类别对象投影到其ID中。
See here for an example of how to create a custom filter in angularjs. 有关如何在angularjs中创建自定义过滤器的示例,请参见此处 。
you can use underscorejs's _.pluck
method. 您可以使用underscorejs的_.pluck
方法。
selectedCategories = _.pluck(_.filter(categoriesTree, function(category) {
return category.selected;
}), 'id');
which returns an array of the values of all the id
's where the corresponding selected
value is true
. 它返回所有id
的值的数组,其中对应的selected
值是true
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.