Angular JS - angular.forEach - Как получить ключ от объекта?
У меня есть объект JSON, как показано ниже
{
"txt_inc_Application": {
"EWS": true,
"EWindow": true
},
"txt_inc_IncidentType": {
"Brand Damage": true,
"Internal failure": true
}
}
И я использую angular.forEach для получения значений
$scope.filterFormula=function() {
angular.forEach($scope.filters, function(filterObj , filterIndex) {
angular.forEach(filterObj, function(value , key) {
console.log(value+"--"+key)
})
})
}
Как я могу получить "txt_inc_Application" и "txt_inc_IncidentType" в цикле?
Также, когда вы вызываете функцию angular в html, как показано ниже, почему она выполняется дважды?
{{filterFormula()}}
![enter image description here]()
Ответы
Ответ 1
Первым параметром для итератора в forEach
является значение, а второй - ключ объекта.
angular.forEach(objectToIterate, function(value, key) {
/* do something for all key: value pairs */
});
В вашем примере внешний forEach на самом деле:
angular.forEach($scope.filters, function(filterObj , filterKey)
Ответ 2
var obj = {name: 'Krishna', gender: 'male'};
angular.forEach(obj, function(value, key) {
console.log(key + ': ' + value);
});
дает атрибуты obj
с их соответствующими значениями:
name: Krishna
gender: male