ZK-2500z
ZK-2500z

Reputation: 63

How to iterate through firebase object childeren

I am new to firebase and javascript but I am trying to iterrate through my firebase database which really just has 1 object and some childeren under it. I followed some tutorials but feel like im in a rabbit hole right now. I only get the top levels back and not the childeren

enter image description here

This is what i tried:

var ref = database.ref('Exercise');
ref.on('value', gotData, errData);

function writeData(){
    firebase.database().ref("Exercise").set({
        nameExercise: exerciseName.value,
        setAm: setAmount,
//        setAm: {
  //          HoeveelheidArr,
    //        Gewicht,
        //}
        repetitie: Gewicht,
        hoeveelheidKilogram:Gewicht,

    });
}


var ref = database.ref('Exercise');
ref.on('value', gotData, errData);

function gotData(data){
    //console.log(data.val());
    var exercise = data.val();
    var keys = Object.keys(exercise);
    console.log(keys);
    for( var i = 0; i < keys.length; i++){
        var k = keys[i];
        var exerciseID = scores[k].nameExercise.value;
        var sets = scores [k].setAm.value;
        var reps = scores[k].repetitie.value;
        var kg = scores [k].hoeveelheidKilogram.value;
        console.log(exerciseID, sets,reps,kg);
    }
}

function errData(err){
    console.log('Error!');
    console.log(err);
}

the write function works well but not the gotData where im trying to display every value of the object in the console:

enter image description here

but all im getting back is teh variable names from the writeData function. Do you see what i do wrong?

Upvotes: 0

Views: 58

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598886

As far as I can see you have only a single exercise under /Exercise, which means that the for( var i = 0; i < keys.length; i++){ loop is not needed.

An example of how to access/log various parts of your JSON:

function gotData(data){
    var exercise = data.val();
    console.log(exercise);
    console.log(exercise.hoeveelheidKilogram);
    exercise.hoeveelheidKilogram.forEach(function(value) {
        console.log(value);
    });
}

Upvotes: 1

Related Questions