如何在Typescript中动态访问此JSON元素?

时间:2018-01-23 13:08:59

标签: json angular typescript

我有一个在整个应用程序中使用的数据网格。我正在使用以下代码获取当前选定的rowid。

在HTML中:

<tbody>
   <tr *ngFor="let ddata of tableData.data; let i = ddata" (click)="setClickedRow(ddata)" [class.active]="ddata.discountauthorizationid == selectedRow">
      <td *ngFor="let dr of tableData.record | paginate: { itemsPerPage: pageItem, currentPage: p }">{{ddata[dr]}}</td>
   </tr>
</tbody>

component.ts文件中,我这样做:

this.selectedRow = ddata.discountauthorizationid;

console.log("You selected!",ddata.discountauthorizationid);
this.dataService.changeMessage(ddata.discountauthorizationid);

现在我想让这个访问完全动态化,我有像这样定义的主要ID

@Input() primaryid: string

我想访问此data.(some_primaryid)就像我们使用key访问数组并使用变量分配键一样。可能吗?如果是这样的话?

3 个答案:

答案 0 :(得分:1)

以下是您访问该值的方法。

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.primaryId = "userId";
    
    $scope.data = {
       "userId": 1,
       "accountId": 23,
       "testId": 5
    };

  
$scope.changeId = ()=>{
    
   $scope.primaryId = "accountId";
};
}
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myApp">
<div ng-controller="MyCtrl">
   {{primaryId}} is :  {{data[primaryId]}}!
 <button ng-click="changeId()">
  Change ID
 </button>
</div>
</body>
</html>

答案 1 :(得分:0)

更新,根据您的评论:

class Data {
    public some_primary_id: string;
}

let id = 'some_primary_id'; // id would be your input parameter
let data = <Data>{ some_primary_id: '123' };

alert(data[id]); // 123

以前的评论: 我不确定我的问题是否正确,但根据你的最后一句话:

  

想要访问这些数据。(some_primaryid)就像我们使用key访问数组并使用变量分配键一样。可能吗?如果是这样的话?

是的,您可以访问以下属性:

console.log(ddata['some_primaryid']);
ddata['some_primaryid'] = '123';

答案 2 :(得分:0)

尝试了很多事情。我能够这样做。 DDATA [primary_id_var]。 我尝试了ddata [{{primary_id_var}}],但它没有用。

相关问题