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

时间:2023-02-09 02:31:01

I have JSON object like below

我有像下面这样的JSON对象

{
    "txt_inc_Application": {
        "EWS": true,
        "EWindow": true
    },
    "txt_inc_IncidentType": {
        "Brand Damage": true,
        "Internal failure": true
    }
}

And I am using angular.forEach to get the values

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

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

How can i get "txt_inc_Application" and "txt_inc_IncidentType" in the loop?

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

Also when call the angular function in html like below why it is getting executed twice?

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

{{filterFormula()}}

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

2 个解决方案

#1


47  

The first parameter to the iterator in forEach is the value and second is the key of the object.

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

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

In your example, the outer forEach is actually:

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

angular.forEach($scope.filters, function(filterObj , filterKey)

#2


2  

var obj = {name: 'Krishna', gender: 'male'};
angular.forEach(obj, function(value, key) {
    console.log(key + ': ' + value);
});

yields the attributes of obj with their respective values:

产生obj的属性及其各自的值:

name: Krishna
gender: male

#1


47  

The first parameter to the iterator in forEach is the value and second is the key of the object.

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

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

In your example, the outer forEach is actually:

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

angular.forEach($scope.filters, function(filterObj , filterKey)

#2


2  

var obj = {name: 'Krishna', gender: 'male'};
angular.forEach(obj, function(value, key) {
    console.log(key + ': ' + value);
});

yields the attributes of obj with their respective values:

产生obj的属性及其各自的值:

name: Krishna
gender: male