A beginner's guide to retrieving random names and images from JSON data for every object using JavaScript

I have a creative idea for a random ruffling game, where it picks a user's name and image randomly.

However, I'm facing an issue with ensuring that each image matches the correct user when selected randomly.

I want to make sure that every object in the json array with a name and image is properly matched during the random selection process.

How can I achieve this?

Here is my code:

script.js
    const ENTRANTS = [{
      name:"John",
      image:"images/sun-rise.jpg"
      },{
        name:"Jack",
        image:"images/tree-736885__480.jpg"
      },{
        name:"Jane",
        image:"images/pexels-anjana-c-674010.jpg"
      }];
     
    const rollEl = document.querySelector(".roll");
    const rollAgainEl = document.querySelector(".roll-again");
    const namesEl = document.querySelector(".names");
    const imageEl = document.querySelector(".image");
    const winnerEl = document.querySelector(".winner");
    const boxEl = document.querySelector(".text-box");
    const winnerTextELEMENT = document.querySelector(".winnerText");
    const values = Object.values(ENTRANTS)
    winnerTextELEMENT.classList.add('hide')
    function randomName() {
      const rand = Math.floor(Math.random() * values.length);
      const name = values[rand].name;
      const image = values[rand].image;
    
      namesEl.innerText = name;
      imageEl.src = image
    }
    
    function rollClick() {
      boxEl.classList.remove("hide")
      rollEl.classList.add("hide");
      rollAgainEl.classList.add("hide");
      winnerEl.classList.add("hide");
      namesEl.classList.remove("hide");
    
      setDeceleratingTimeout(randomName, 10, 30);
    
      setTimeout(() => {
        namesEl.classList.add("hide");
        winnerEl.classList.remove("hide");
        rollAgainEl.classList.remove("hide");
    
        const winner = namesEl.innerText;
        winnerEl.innerText = winner;
        winnerTextELEMENT.classList.remove('hide')
      }, 4000);
    }
    
    function setDeceleratingTimeout(callback, factor, times) {
      const internalCallback = ((t, counter) => {
        return () => {
          if (--t > 0) {
            setTimeout(internalCallback, ++counter * factor);
            callback();
          }
        };
      })(times, 0);
    
      setTimeout(internalCallback, factor);
    }

index.html:

<!DOCTYPE html>
<html lang="en" >
  
<head>
  <meta charset="UTF-8">
  <title>Ruffle</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
  <link rel="stylesheet" href="./style.css">
</head>

<body>

  <button class="roll" onclick="rollClick()">Start</button>


    <span class="winnerText">WINNER</span>
    <div class="text-box hide">
      <img class="image" src=""/>
      <div class="names hide">

    </div>
      <div class="winner hide"></div>
    </div>

    <button class="roll-again hide" onclick="rollClick()"> Start Again</button>
    <script  src="./script.js"></script>

</body>

</html>

Answer №1

To spice things up, generate two arrays by combining both names and images values in a unique way. Implement Math.Floor(Math.random * array.length) for both arrays to acquire a random value that can serve as an index within the array. Subsequently, utilize this randomly generated index value to access a name and picture at random.

Answer №2

To retrieve the desired image and name from JSON data in Javascript, first convert the JSON into an array. Then use the following code:

MyArray[Math.round((Math.random()*number) * 10000) / 10000]
. This will help you select the specific content you are looking for.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to upload the file using AJAX

Here is my AJAX request where I am attempting to send form data to a PHP page and display messages accordingly. The problem I'm encountering is that when using serialize() method in AJAX, my file data is not being posted. As a result, the send.php scr ...

Webpack loaders or plugins: understanding the distinction

Can you explain the distinction between loaders and plugins in webpack? I found on the documentation for plugins that it states: Plugins are used to incorporate extra functionalities usually related to bundles within webpack. While I understand that b ...

exploring XML documents

With around 250,000 XML files, each named with a UUID, I am looking for the most effective way to perform a full text search on these files and identify the UUID of the matching ones. What would be the optimal approach for indexing them in a nodejs environ ...

Display a div every 3 seconds with the help of jQuery

I am seeking a solution to display the second div (box2) every 3 seconds. Can anyone help me achieve this using jQuery? <div id="box1" style="background-color:#0000FF"> <h3>This is a heading in a div element</h3> <p>This ...

What is the procedure for sending JSON data to a URL using AJAX?

<script> var postData = JSON.stringify({"S":"Sam"}); $.ajax({ type: 'POST', url: '/view', data: postData, contentType: "application/json; charset=utf-8", dataType: 'json', success: function(data) ...

Adjust the background color of a list item using Typescript

At the top of my page, there's a question followed by a list of answers and the option to add new ones. You can see an example in the image below. https://i.stack.imgur.com/NPVh7.jpg The format for each answer is "(username)'s response: at this ...

Accessing a JSON file from AWS S3 using Node.js

I was able to successfully read a JSON file stored in my S3 bucket, but I found myself having to perform various transformations that are somewhat unclear to me. When logging the data as it arrives, I am seeing an output of Buffer data s3.getObject(objPar ...

To make the down arrow image scroll to the end of the page after the 2nd click, simply follow these steps. Initially, the first click

After setting up the image icon and utilizing Javascript and jQuery, I encountered an issue with the down arrow functionality. The first click successfully takes me to the second row grid box downwards, but I am struggling to implement a second click actio ...

Exploring i18nNext integration with antd table in React

Presently, this is the UI https://i.stack.imgur.com/CMvle.png App.tsx import "./styles.css"; import MyTable from "./MyTable"; export default function App() { const data = [ { key: "1", date: "2022-01- ...

struggling to retrieve a value from a jsonArray

Currently, I'm utilizing gson for json parsing in my project and dealing with a com.google.gson.jsonArray. JsonObject object = jelement2.getAsJsonObject().getAsJsonObject("fields"); JsonArray jArray = (JsonArray) object.get("entity_facets"); Here ...

Different Ways to Access an Array in an EJS Template

After receiving a list of IDs from an API, I need to include them in a URL within an EJS template to retrieve the correct items. For example, the URL format is: Here are some example IDs: 526 876 929 The desired output inside the EJS template: <li&g ...

Issue with Material-ui IconButton's edge properties not functioning as expected

Is there a way to position the delete icon on the right side of the screen? It seems like using edge= "end" is not working as expected. If you'd like to take a look, here is the sandbox link: https://codesandbox.io/s/admiring-silence-vwfoe? ...

Fetching all data from a SQLite database in a Listview using React Native

I have been utilizing the library found at https://github.com/andpor/react-native-sqlite-storage in my react native project. To retrieve a single row from the database, I use the following code: db.transaction((tx) => { tx.executeSql('SEL ...

What is the difference in performance between using named functions versus anonymous functions in Node.js?

Currently, I am working on a Node.js app and was initially using anonymous functions for callbacks. However, after referring to the website callbackhell.com, I discovered that using named functions is considered best practice for coding. Despite switching ...

Neglecting to review the CSS - embracing ejs layouts in Express

I am encountering an issue with the express ejs layouts where only the mainPage is able to read the CSS, while the other pages are unable to do so (even though the HTML reads it). Additionally, if I want to use another layout such as "layout2.ejs", what s ...

Initiating a horizontal scroll menu at the center of the screen: Step-by

I need assistance setting up a horizontal scrolling menu for my project. The requirement is to position the middle button in the center of the .scrollmenu div. Currently, I am working with HTML and CSS, but open to suggestions involving javascript as well ...

"Resetting the state of a form in AngularJS2: A step-by

Looking to reset the form state from dirty/touched in angular? I am currently delving into the world of angular2 and working on a form with validation. In my journey, I came across this code snippet: <form *ngIf="booleanFlag">..</form> This ...

I am encountering issues with my JavaScript files that appear to be following the correct path, however they are not functioning properly. Error messages such as SyntaxError: expected expression

I am currently working on a Yii2 application. My goal is to utilize the JavaScript and CSS files from the common folder in my backend. The paths for these files are within the common/web/js and common/web/css directories respectively. To achieve this, I ...

What are some reasons for the slow performance of AWS SQS?

My current project involves measuring the time it takes to send a message and receive it from an SQS queue. Surprisingly, the average time it takes is between 800-1200 ms, which seems like an excessively long period. Below is the code I have been using for ...

I am having trouble displaying the background on my website using css/html

I'm currently working on enhancing my website BJBGaming1.com, and I've encountered an issue with setting a background. Here's the code snippet I have: <!doctype html> <html class="no-js" lang="en"> <head> <meta charset= ...