简体   繁体   English

Angular JS +使用$ filter从对象列表中获取属性到Array中

[英]Angular JS + get an attribute from a list of objects into Array using $filter

I need get specific attributes from items within a array of objects. 我需要从对象数组中的项目中获取特定属性。

Example

var arrayOfObjects = [
  {"name":"as","code":"9874"},
  {"name":"sd","code":"9541"},
  {"name":"df","code":"1574"},
  {"name":"fg","code":"5874"},
  {"name":"gh","code":"3652"},
  {"name":"hj","code":"1452"}
]

Result 结果

var newArrayOfObjectsFiltered = [
  {"code":"9874"},
  {"code":"9541"},
  {"code":"1574"},
  {"code":"5874"},
  {"code":"3652"},
  {"code":"1452"}
]

As you can see, I want the code property from each object in the list. 如您所见,我想要列表中每个对象的code属性。

I already tried the following but it doesn't work: 我已经尝试了以下方法,但是不起作用:

var filteredArray = filterFilter(arrayOfObjects, 'code');

You need custom filter like this 您需要这样的自定义过滤器

app.filter('myFilter, 'function(){
  return function(array){
    if(!arrayOfObjects) return [];
    return arrayOfObjects.map(function(obj){
      return { "code": obj.code }
    })
  }
})

I would not even use a filter for that unless you need it in one of your templates. 除非您在一个模板中需要它,否则我什至不会使用过滤器。 If you only filter things in your controller or service you can simply use Array.prototype.map() and reminds of a more functional way. 如果只过滤控制器或服务中的内容,则可以简单地使用Array.prototype.map()并提醒您一种更实用的方法。 In combination with utility libraries like lodash you can do it as follows: lodash类的实用程序库结合使用,您可以执行以下操作:

arrayOfObjects.map(function(item) {
    return _.pick(item, 'code');
});

Pick only takes the specified properties. 选择仅采用指定的属性。

_.pick(object, [predicate], [thisArg]) _.pick(object,[predicate],[thisArg])

Creates an object composed of the picked object properties. 创建一个由拾取的对象属性组成的对象。 Property names may be specified as individual arguments or as arrays of property names. 属性名称可以指定为单个参数或属性名称数组。 If predicate is provided it's invoked for each property of object picking the properties predicate returns truthy for. 如果提供了谓词,则为对象的每个属性调用该谓词,选择该谓词将返回真值。 The predicate is bound to thisArg and invoked with three arguments: (value, key, object). 谓词绑定到thisArg,并使用三个参数调用:(值,键,对象)。

Update 1 更新1

In case you need it in a template, eg to filter a collection passed to ng-repeat you can simply insert the code snippet into a custom filter like so: 如果您需要在模板中使用它,例如,过滤传递给ng-repeat的集合,则只需将代码段插入自定义过滤器中即可,如下所示:

angular.module('app', []).filter('myCustomFilter', function() {
    return function(input, properties) {
        return input.map(function(item) {
            return _.pick(item, properties);
        });
    };
});

You can then use it like so: 然后可以像这样使用它:

<li ng-repeat="item in arrayOfObjects | myCustomFilter:['code']"></li>

The result will be that each item only has the specified properties. 结果将是每个项目仅具有指定的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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