如何从数组中获取特定对象的属性?

问题描述:

我需要从数组中获取具有特殊属性“类型”的对象。这些对象我将分配给范围。我怎样才能做到这一点?如何从数组中获取特定对象的属性?

下面的方法对我来说没有解决。

$scope.vendors = {} 
$scope.clients = {} 

$scope.loadCounterparties = function() { 
    Counterpartie.query(function(response) { 

    $scope.vendors = response.type.Vendor; 
    $scope.clients = response.type.Client 

    }); 
}; 

响应物体看起来像这样

enter image description here

提前感谢!

Angular没有专门的东西。您需要通过纯java脚本过滤数组。然而,你可以尝试使用3rd party library by the name underscore.js. 它增加了许多有用的功能,如“在哪里”:

_.where(列表属性) 会仔细检查该列表中的每个值,返回所有包含所有的值的数组属性中列出的键值对。

_.where(listOfPlays,{author:“Shakespeare”,year:1611}); => [{标题: “辛白林”,作者: “莎士比亚”,年:1611}, {标题: “暴风雨”,作者: “莎士比亚”,年:1611}]

这里是图书馆的网页 http://underscorejs.org/#where

+0

谢谢你,丹尼斯! –

链接可以使用角度的forEach,但我会用lodash

// assuming one array and two search arguments i.e. client and vendor 
var data = response; 
$scope.loadCounterparties = _.filter(data, {type: 'Vendor', type:  'Client'});