[英]How to select property from object in javascript using a variable containing the property name
在AngularJS控制器中,我創建了一個發出JSONP請求的函數。 該請求返回一個JSONP對象,其格式如下。
[{
"Domain_1":{
"Notes":"This information can be usefull for generic information",
"Contacts":[
{
"ContactName":"P. rimary",
"ContactPhone":"+31 612 273 88"
}
]
},
"Domain_2":{
"Notes":"This information can be usefull for generic information",
"Contacts":[
{
"ContactName":"S. secondary",
"ContactPhone":"+31 612 273 88"
}
]
}
}];
在以下函數中發出JSONP請求時,將成功返回該對象。 ($ scope.method和$ scope.domainName在范圍級別設置)我想要實現的是選擇與$ scope.domainName中的值匹配的JSON數據的特定部分,並將其分配給范圍變量$ scope。 domainData。
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
// Only make JSONP request if domain name is known
if ($scope.domainName !== null) {
$http({method: $scope.method, url: $scope.url, timeout: 5000}).
success(function(data, status) {
$scope.status = status;
console.log("Data:") ; console.dir(data) ;
console.log("Domain Name" + $scope.domainName) ;
$scope.domainData = data[$scope.domainName] ;
console.log("DomainData: ") ;
console.dir($scope.domainData) ;
}).
error(function(data, status, headers, config) {
$scope.domainData = null ;
$scope.status = status;
console.log("$scope.fetch failed" + $scope.status + " :: " + data) ;
});
} else {
console.log("Shame... nothing to do..... ") ;
}
};
當執行代碼時,域名為“ Domain_1”,並且包含數據(顯示在控制台中);
0: Object
Domain_1: Object
Contacts: Array[1]
0: Object
ContactName:"P. rimary"
ContactPhone:"+31 612 273 88"
...
但是$ scope.domainData是未定義的。 如何使此選擇正常工作?
根據封裝的方括號,您的響應對象似乎是頂層的數組。 這意味着您將無法直接使用域名取消引用。 解決此問題的一種方法是在您的成功功能中類似於以下內容:
$scope.domainData = data[0][$scope.domainName];
當然,僅在始終確定響應對象是長度為1的數組(如您的示例)時,才建議將其硬編碼為0
。 如果情況並非總是如此,則可能必須實現某種迭代遍歷以尋找匹配的屬性。
要訪問響應中的數據,您應該訪問響應的data屬性。
...
$http({method: $scope.method, url: $scope.url, timeout: 5000}).
success(function(response, status) {
...
# With the latest versions of angularJs (I don't know in which
# version was that), the data is in the
# response's data property
$scope.domainData = response.data[$scope.domainName] ;
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.