繁体   English   中英

如何使用包含属性名称的变量从javascript对象中选择属性

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM