如何遍历此Firebase JSON?

时间:2017-10-05 21:37:17

标签: json angular firebase firebase-realtime-database

这是我在Firebase数据库中上传的JSON内容。 现在我需要在我的Angular 2应用程序中访问它。 在尝试访问对象时,我得到了undefined和NaN。

{
      "clients" : {
        "clients" : {
          "-Kdl_wRRkn7nJxgz4B54" : {
            "balance" : "100.00",
            "email" : "jdoe@gmail.com",
            "firstName" : "John",
            "lastName" : "Doe",
            "phone" : "555-555-5555"
          },
          "-KdleehAQm0HgVFYdkUo" : {
            "balance" : "350.00",
            "email" : "stevesmith@gmail.com",
            "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 个答案:

答案 0 :(得分: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" : "jdoe@gmail.com",
      "firstName" : "John",
      "lastName" : "Doe",
      "phone" : "555-555-5555"
     },
     {
       "id" : "-KdleehAQm0HgVFYdkUo",
       "balance" : "350.00",
       "email" : "stevesmith@gmail.com",
       "firstName" : "Steve",
       "lastName" : "Smith",
       "phone" : "444-444-4444"
     }
   ]
}