I have a JSON object like so:
{
"workouts":
[
{
"title": "Full Body",
"exercises":
[
{
"name": "Push Ups",
"duration": 3,
"break": 3
},
{
"name": "Squats",
"duration": 3,
"break": 3
},
{
"name": "Running in Place",
"duration": 3,
"break": 3
}
]
},
{
"title": "God Legs",
"exercises":
[
{
"name": "Running in Place (High Knees)",
"duration": 3,
"break": 3
},
{
"name": "Squats",
"duration": 3,
"break": 3
},
{
"name": "Clams",
"duration": 3,
"break": 3
}
]
},
{
"title": "Morning Stretch",
"exercises":
[
{
"name": "Downward Dog",
"duration": 3,
"break": 3
},
{
"name": "Face Plant",
"duration": 3,
"break": 3
},
{
"name": "Warrior",
"duration": 3,
"break": 3
}
]
}
]
}
I can loop through the titles and append them to the body, now I would like to loop through each object contained in the "exercises" array and print out each value: name, duration and break, per object. I am not having much success and I wonder if I should change my JSON structure or if I am making some silly mistake in my loops. I am using Firebase by the way, no AJAX calls or such like.
JavaScript:
// Initialize firebase.
firebase.initializeApp(config);
var dbRef = firebase.database().ref().child("workouts");
// Sync with Firebase in real time.
dbRef.on("value", snap =>
{
var workouts = snap.val();
// HAVE A LOOP FOR EVERY ARRAY INJSON.
for (var i = 0; i < workouts.length; i++)
{
window.alert(i + workouts[i].title); // Works fine.
var obj = workouts[i].exercises;
for (obj in workouts)
{
alert(obj.name); // Returns undefined for each object.
}
}
});
var obj = workouts[i].exercises;and replacefor (obj in workouts)withfor (obj in workouts[i].exercises). You're overwriting theobjvariable and looping over the wrong array unless I'm misstaken.