从Firebase检索带有区分子节点的节点

时间:2019-04-27 17:32:02

标签: swift firebase firebase-realtime-database

我有以下json树:

{
"workout" : {
 "Monday, 22 Apr, 2019" : {
  "exercise" : {
    "Chest Press Machine" : {
      "-Ld5FCV-q_pnPvT9MICU" : {
        "reps" : "10",
        "set" : "1",
        "weight" : "70"
      },
      "-Ld5FJDqxepyhCN3twrM" : {
        "reps" : "8",
        "set" : "2",
        "weight" : "75"
      }
    },
    "Decline Dumbbell Bench Press" : {
      "-Ld5SCZhUpmrnBYhw-xK" : {
        "reps" : "8",
        "set" : "1",
        "weight" : "24"
      }
    },
    "Incline Barbell Bench Press" : {
      "-Ld3wdB0mKZB9hEJ_9gF" : {
        "reps" : "8",
        "set" : "1",
        "weight" : "55"
      }
    }
  }
},
"Saturday, 27 Apr, 2019" : {
  "exercise" : {
    "Decline Dumbbell Flyes" : {
      "-LdTqpAEpVaE8VHVH_Hq" : {
        "reps" : "10",
        "set" : "1",
        "weight" : "10"
      }
    }
  }
}

如何从日期不同的每个锻炼课程中检索锻炼名称,即“胸肌推举机”和“下降哑铃卧推”?我打算将这些值排序在数组“ exerciseList”中。

到目前为止,我已经使用下面的代码在一个日期内检索了演习,但我不知道如何指定名称。

refExerciseList.child("workout").observe(DataEventType.value, with: {(snapshot) in
        let items = snapshot.value as! [String: Any]
        print(snapshot)
        for i in Array(items.values){
            print(i)
        }
    })

谢谢。

1 个答案:

答案 0 :(得分:2)

您可以尝试

var exerciseList = [String]()
refExerciseList.child("workout").observe(DataEventType.value, with: {(snapshot) in
        let items = snapshot.value as! [String: [String:[String:Any]]]
        print(snapshot)
        for i in Array(items.values){
           for inner in Array(i.values){
             exerciseList += Array(inner.keys)
           }
        }
})