Hello All!
I am currently attempting to build a site that generates a random meal upon clicking the “generate” button. Attached below will be my code. The issue I am running into is the following; upon clicking the generate button, I am met with numbers, instead of names and nutrition values. I recognize that this is what the Math.random() and Math.floor() are doing - but why is this not converted to an index referencing the food in question? Any help is appreciated. Thank you. For an example of how this should (ideally) work, I will provide a link to a similar project, that has been completed by another user.
Javascript:
// Food(s) array w/nested Objects. //
const foods = [
{ "name": 'Chicken and Rice',
"protein": '45g',
"fat": '12g',
"carbohydrates" : '35g',
"total calories": '428'
},
{ "name":'Guac Omelette',
"protein":'30g',
"fat":'20g',
"carbohydrates":"17g",
"total calories": '368'
},
{
"name":"beef rice",
"protein":'48g',
"fat":'22g',
"carbohydrates":'52g',
"total calories":'598'
}
]
for (let i=0; i<foods.length; i++){
console.log(foods[i])
}
function getFood()
{
let randomFood = [Math.floor(Math.random()*foods.length)];
document.getElementById("randpick").textContent=randomFood;
}
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Random Meal Generator</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1 class="question">Feeling Hungry?</h1>
<h2 class="question">
Struggling to come up with healthy meals?
</h2>
<button class="generate" id="generate" onclick="getFood()">
Click Me To Generate a Random Meal!
</button>
<p class="info">
A balanced macronutrition dietary profile is of utmost importance for overall health and well-being. It refers to the consumption of an appropriate ratio of macronutrients, including carbohydrates, proteins, and fats, in the right proportions. Such a diet provides the body with essential nutrients, energy, and the building blocks necessary for various bodily functions.
</p>
<p id = "randpick">
Alpha Omega
</p>
</div>
<script src="logic.js"></script>
</body>
</html>