I want to loop through the JSON file - I believe it is an array of objects. For each object, I want to get the 'name' property as well as the name of each ingredient and its value (in string form) to display in it's own div. JSON file and JS code follow. No matter what I do I cannot seem to loop and access the properties successfully.
JSON
[{
"name": "Rum & Coke",
"ingredients": {
"rum": 50,
"coke": 150
}
},
{
"name": "Gin & Tonic",
"ingredients": {
"gin": 50,
"tonic": 150
}
},
{
"name": "Long Island",
"ingredients": {
"gin": 15,
"rum": 15,
"vodka": 15,
"tequila": 15,
"coke": 100,
"oj": 30
}
},
{
"name": "Screwdriver",
"ingredients": {
"vodka": 50,
"oj": 150
}
}
]
const data = require('./drinkList.json')
const data = JSON.parse(data)
var mainContainer = document.getElementById("drinks");
for (let i in data) {
var div = document.createElement("div");
div.setAttribute("class", "DrinkContainer")
var drinkName = document.createElement("p")
drinkName.setAttribute("class", "DrinkName")
drinkName.innerHTML = data[i]['name']
div.appendChild(drinkName);
var drinkIngredients = document.createElement("p")
drinkIngredients.setAttribute("class", "DrinkIngs")
const ingredientsInDrink = data[i]['ingredients']
let ingNameArray = Object.keys(ingredientsInDrink)
for (const x in ingNameArray) {
for (const amount in ingredientsInDrink[x]) {
const ing = x;
const ingAmount = amount.toString();
const stringForIngredients = ingAmount + "mls of " + ing
}
}
drinkIngredients.innerHTML = stringForIngredients
div.appendChild(drinkIngredients)
mainContainer.append(div)
}