如何访问对象的数据?

时间:2019-09-02 06:31:02

标签: angular typescript firebase

我有一个从Firebase读取数据的功能。我可以读取对象,但不能读取属性。

我尝试解析内容,但是出现错误。

这是功能:

 this.afAuth.authState.subscribe(data => {
            this.itemsList = this.afDatabase.list(`oders/${data.uid}`).valueChanges();
            
            console.log(this.itemsList)
            this.itemsList.forEach(data =>{
              console.log(data) // this work
              console.log(data.name) // this doesn't work (undifined in console)
            })
          })

我的JSON OBJECT

(14) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {hour: 1567395936608, id: 0, name: "Salami", price: "8"}
1: {hour: 1567395936608, id: 9, name: "Suplémment Fromage", price: "8"}
2: {hour: 1567395936608, id: 4, name: "bolo", price: "8"}
3: {hour: 1567395936608, id: 4, name: "bolo", price: "8"}
4: {hour: 1567395985542, id: 4, name: "bolo", price: "8"}
5: {hour: 1567395985542, id: 0, name: "Salami", price: "8"}
6: {hour: 1567395985542, id: 9, name: "Suplémment Fromage", price: "8"}
7: {hour: 1567397849623, id: 6, name: "Dems", price: "15"}
8: {hour: 1567397849623, id: 0, name: "Salami", price: "8"}
9: {hour: 1567397849623, id: 9, name: "Suplémment Fromage", price: "8"}
10: {hour: 1567398309241, id: 0, name: "Salami", price: "8"}
11: {hour: 1567398309241, id: 9, name: "Suplémment Fromage", price: "8"}
12: {hour: 1567402336588, id: 0, name: "Salami", price: "8"}
13: {hour: 1567402336588, id: 9, name: "Suplémment Fromage", price: "8"}

谢谢!

2 个答案:

答案 0 :(得分:1)

由于data本身就是数组,因此您需要运行另一个循环

尝试这样:

this.itemsList.forEach(data =>{
   this.data.forEach(e=>{
       console.log(e.name) 
   })
})

或者您可以这样做:

this.itemsList[0].forEach(data =>{
    console.log(data.name) 
})

答案 1 :(得分:0)

使用传播算子。

[...this.itemsList].forEach(item) {
 console.log(item.hour);
}