gcpreston
gcpreston

Reputation: 135

Retrieving nodes from Firebase with differentiating child nodes

I have the following json tree:

{
"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"
      }
    }
  }
}

How can I retrieve the exercise names i.e "Chest Press Machines" and "Decline Dumbbell Bench Press" from each of the workout sessions with different dates? I aim to sort these values in an array "exerciseList".

So far I have used the code below to retrieved the exercises within a date but I don't know how to target the name.

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)
        }
    })

Thanks in advance.

Upvotes: 0

Views: 29

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

You can try

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)
           }
        }
})

Upvotes: 2

Related Questions