简体   繁体   English

如何使用AngularJS过滤对象属性

[英]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过滤器有关吗?

res = categoriesTree.map(function(el) { return el.id; });

Short and simple, with the good ole js. 简短而简单,带有良好的ole js。

To answer your question: no, with filters you can't, but it is possible with forEach 要回答您的问题:不,使用过滤器无法实现,但是forEach可以实现

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM