Angular JS - angular.forEach - 如何获取对象的键?

Sar*_*nan 22 angularjs

我有像下面这样的JSON对象

{
    "txt_inc_Application": {
        "EWS": true,
        "EWindow": true
    },
    "txt_inc_IncidentType": {
        "Brand Damage": true,
        "Internal failure": true
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用angular.forEach来获取值

$scope.filterFormula=function() {
    angular.forEach($scope.filters, function(filterObj , filterIndex) {
        angular.forEach(filterObj, function(value , key) {
            console.log(value+"--"+key)
        })
    })
}
Run Code Online (Sandbox Code Playgroud)

如何在循环中获得"txt_inc_Application"和"txt_inc_IncidentType"?

另外当调用html中的angular函数时,为什么它会被执行两次?

{{filterFormula()}}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

0xc*_*0de 48

迭代器的第一个参数forEach是值,第二个是对象的键.

angular.forEach(objectToIterate, function(value, key) {
    /* do something for all key: value pairs */
});
Run Code Online (Sandbox Code Playgroud)

在您的示例中,外部forEach实际上是:

angular.forEach($scope.filters, function(filterObj , filterKey)
Run Code Online (Sandbox Code Playgroud)