获取嵌套数组中特定键的每个值的总量

时间:2016-06-23 21:36:16

标签: javascript arrays angularjs

数组

[
    {
        id: 1,
        title: "Test 1",
        eventTypeId: 2,
        eventType: {
            id: 2,
            name: "Event X",
            category: {
                id: 1, 
                name: "Study 1"
            }
        }
    },
    {
        id: 2,   
        title: "Test 2",
        eventTypeId: 2,
        eventType: {
            id: 2,
            name: "Event Y",
            category: {
                id: 1,
                name: "Study 2"
            }
        }
    },
    {
        id: 3,
        title: "Test 3",
        eventTypeId: 2,      
        eventType: {
            id: 2,
            name: "Event Z",
            category: {
                id: 2,
                name: "Study 1"
            }
        }
    }
];

数据来自API请求,成功function内部我将响应归因于$scope.initialDataLength,如下所示:

var getDataLength = function () {
    $http.get(urlData).success(function (data) {
       $scope.initialDataLength = data;
    }
}

查看

<td class="col-md-2">
   {{ initialDataLength.length }}
</td>

但我希望获得name对象Category的长度。

我正在尝试类似的事情:

angular.forEach (data, function (typeId) {
    var type = typeId.eventType;
    angular.forEach (type, function (category) {
        var cat = category.name;
        console.log("cat", cat.length)
    })
});

但它显示以下错误:

  

无法读取未定义的属性“长度”

有人能解释我,我的错误在哪里?

1 个答案:

答案 0 :(得分:2)

你不需要内在的forEach()。您已经拥有了对象引用,只需要访问该对象的属性

angular.forEach (data, function (typeId) {

    console.log(typeId.eventType.category.name)

});