2017-10-05 53 views
0

這是我在Firebase數據庫中上傳的JSON內容。 現在我需要在我的Angular 2應用程序中訪問它。 我正在嘗試訪問對象時未定義和NaN。如何迭代此Firebase JSON?

{ 
     "clients" : { 
     "clients" : { 
      "-Kdl_wRRkn7nJxgz4B54" : { 
      "balance" : "100.00", 
      "email" : "[email protected]", 
      "firstName" : "John", 
      "lastName" : "Doe", 
      "phone" : "555-555-5555" 
      }, 
      "-KdleehAQm0HgVFYdkUo" : { 
      "balance" : "350.00", 
      "email" : "[email protected]", 
      "firstName" : "Steve", 
      "lastName" : "Smith", 
      "phone" : "444-444-4444" 
      } 
     } 
     } 
    } 

我試圖訪問此這裏

export class ClientsComponent implements OnInit { 
    clients:any[]; 
    totalOwed:number; 

    constructor(
    public clientService:ClientService 
) { } 

    ngOnInit() { 
    this.clientService.getClients().subscribe(clients => { 
     this.clients = clients; 
     console.log(this.clients); 
     this.getTotalOwed(); 
    }); 
    } 

    getTotalOwed(){ 
    let total = 0; 
    for(let i = 0;i < this.clients.length;i++){ 
     console.log(this.clients[i]); 
     total += parseFloat(this.clients[i].balance); 
    } 
    this.totalOwed = total; 
    console.log(this.totalOwed); 
    } 

} 

回答

1

首先,你應該重新構造你的JSON,下面的結構將通過循環更好,更好的做法。其次,你得到的不是數字的原因是因爲你沒有訪問平衡鍵的值。

代碼遍歷下面的數據結構將類似於:

for(let i = 0; i < this.clients.length(); i++) { 
    console.log(this.clients[i].balance) 
} 

和JSON:

{ 
    "clients" : [ 
    { 
     "id" : "-Kdl_wRRkn7nJxgz4B54", 
     "balance" : "100.00", 
     "email" : "[email protected]", 
     "firstName" : "John", 
     "lastName" : "Doe", 
     "phone" : "555-555-5555" 
    }, 
    { 
     "id" : "-KdleehAQm0HgVFYdkUo", 
     "balance" : "350.00", 
     "email" : "[email protected]", 
     "firstName" : "Steve", 
     "lastName" : "Smith", 
     "phone" : "444-444-4444" 
    } 
    ] 
}