Random meal generator

Hello everyone!

This is my second thread dedicated to this project. I am working hard to try and get it to function properly.

I have implemented the random logic - whenever the “generate meal button” is clicked, the Math.Random() + Math.floor() function pulls a random meal from my array, which contains nested objects.

I am having all of the keys and entries popup on the screen each time the user generates a new meal. However, I am having a VERY hard time trying to format this; how would I format the strings that display as a result to not include curly braces, brackets, and be spaced out? Attached below will be all of my JS and HTML.
JS:

// 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 userFood = foods[Math.floor(Math.random()*foods.length)];

    let food = foods.values(foods.name);
let choice = JSON.stringify(userFood)
document.getElementById('randpick').textContent=choice;




console.log(userFood)

}


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>

    <div id = "randomMeal">
<p id = "randpick">

Alpha Omega
</p>

    </div>
   

</div>
    
    
    
<script src="logic.js"></script>
</body>
</html>

You loop the array and use each object and its properties when constructing the HTML string. I’d suggest using template literals. Then you append the resulting HTML string to the DOM.

Edit: I guess in your case you won’t be looping the array as you are getting a single object. But you still need to use the object and its properties.

Here is a simple example, it gets the data from an API but the idea is the same.


YouTube search: dom manipulation in javascript
https://www.youtube.com/results?search_query=dom+manipulation+in+javascript

JavaScript30

1 Like

Have you done the frontend challenges on freeCodeCamp? The random quote generator project is fairly similar to what you are doing here.

Here is a simpler example
const root = document.getElementById("root");

const products = [
  {
    id: 1,
    title: "iPhone 9",
    description: "An apple mobile which is nothing like apple",
    price: 549,
    discountPercentage: 12.96,
    rating: 4.69,
    stock: 94,
    brand: "Apple",
    category: "smartphones",
    thumbnail: "https://i.dummyjson.com/data/products/1/thumbnail.jpg"
  },
  {
    id: 2,
    title: "iPhone X",
    description:
      "SIM-Free, Model A19211 6.5-inch Super Retina HD display with OLED technology A12 Bionic chip with ...",
    price: 899,
    discountPercentage: 17.94,
    rating: 4.44,
    stock: 34,
    brand: "Apple",
    category: "smartphones",
    thumbnail: "https://i.dummyjson.com/data/products/2/thumbnail.jpg"
  },
  {
    id: 3,
    title: "Samsung Universe 9",
    description:
      "Samsung's new variant which goes beyond Galaxy to the Universe",
    price: 1249,
    discountPercentage: 15.46,
    rating: 4.09,
    stock: 36,
    brand: "Samsung",
    category: "smartphones",
    thumbnail: "https://i.dummyjson.com/data/products/3/thumbnail.jpg"
  },
  {
    id: 4,
    title: "OPPOF19",
    description: "OPPO F19 is officially announced on April 2021.",
    price: 280,
    discountPercentage: 17.91,
    rating: 4.3,
    stock: 123,
    brand: "OPPO",
    category: "smartphones",
    thumbnail: "https://i.dummyjson.com/data/products/4/thumbnail.jpg"
  }
];

const singleProduct = products[Math.floor(Math.random() * products.length)];

const productTemplate = `
  <section>
    <h2>${singleProduct.title}</h2>
    <p>${singleProduct.description}</p>
    <img src=${singleProduct.thumbnail}>
  </section>
`;

root.innerHTML = productTemplate;
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.