解析$http result以获得AngularJS中的特定项

Parse $http result to get specific items in AngularJS

本文关键字:AngularJS http result 解析      更新时间:2023-09-26

我从angularJS中的$http GET得到json样式的结果。它看起来像这样:

{
    "meta":{
    "limit":1000,
},
"objects":[
    {
        "custom_pk":"1",
        "linked_client":null,
        "resource_uri":"/api/v1/card_infos/1"
    },
    {
        "custom_pk":"2",
        "linked_client":null
    }, ...

我想有一个数组,其中包含所有的custom_pk值做的事情,如:

$scope.validate_pk = function(val){
    if (val in myArray)
        // do some stuff

如何创建myArray?

您可以像这样提取对象:

var json = ... the javascript object shown in your question
var custom_pks = [];
for (var i = 0; i < json.objects.length; i++) {
    custom_pks.push(json.objects[i].custom_pk);
}
// at this stage the custom_pks array will contain the list of all
// custom_pk properties from the objects property

我更喜欢使用。map()数组函数:

var myArray = json.objects.map(function(item){
    return item.custom_pk;
});

Array.map()接受一个函数作为参数。该函数对数组中的每个值执行一次,并将(item, index, list)作为参数传递。map函数的结果是一个包含传递函数结果的新数组。