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

Issue with fixed positioning on iPad devices

A unique feature we implemented on our site is a small control that is positioned at the bottom of the screen. However, upon viewing the site on an iPad, the control does not stay fixed at the bottom but rather floats in the middle. What's the issue ...

Global Path in Helmet Content Security Policy is not functioning as expected

I recently implemented Helmet to establish content security policies for my web application using Express in the backend. The specific policies are as follows: const express = require("express"); const app = express(); const helmet = require('helmet&a ...

Populate the text box with database values using the first text box entry

Is it possible to automatically fill in textbox values from a database based on the input entered in another text box? For example, when I enter a name, can the Date of Birth be retrieved and populated in the corresponding field? I attempted to follow an ...

Understanding and parsing a JSON Schema using JSON.Net

I would like to use JSON.Net for deserializing this schema. { "color" : { "type" : "String", "description" : "What color would you prefer for your taco?", "required" : false, "default" : "Green", "options" : [ "Green", "Blue", ...

Enhance your Django webpage with real-time updates using AJAX technology

[Revised for Clarity and Detail] The challenge I'm facing is related to the architecture of my project. I have multiple ideas on how to achieve my goal, but I'm stuck on identifying the correct or most efficient approach. To provide more context ...

Resolving negative margin issues in Material UI components through detailed textual guidance

Having an issue with the paragraphs in material-ui components. The problem arises when the text exceeds the dimensions of the component, causing it to spill over as shown in the image below. <Grid container wrap="nowrap" css={[borde,{ ...

Ways to extract information immediately after using the .load method

Is there a way to instantly store data from .load in JavaScript? Whenever I use .load within a JavaScript function to retrieve content from the server and display it on the browser page, the content does not update immediately. It's only when the fu ...

Issue encountered while attempting to load several google charts simultaneously

What do I need? I am in need of two Google charts, one on each tab of the website as shown in the screenshot below: Tabs What seems to be the issue? The second chart is not loading properly and showing mixed information. This can be observed in the scre ...

Looking to pass the `Item Index` to functions within v-list-item-action in Vuetify?

Is there a way to pass the item index as a parameter to the function within the v-list-item-action element? Thank you in advance! <v-list-item v-for="(layer, i) in layers" :key="i"> <template v-slot="{ item, index }& ...

How to handle an empty data response in Angular 2's HTTP service

My ASP.NET web API has a simple method with the following test results: $ curl localhost:5000/Api/GetAllQuestions [{"questionId":0,"value":"qqq","answers":[{"answerId":25,"value":"qwerty"}]}] However, I am encountering an issue in my Angular 2 HTTP serv ...

Retrieving data from PHP MySql Query and importing it into JavaScript

Currently, I am in the process of developing a count-up timer for one of our office dashboards that tracks the time since the last incident or reset. There is a page dedicated to allowing senior admins to input a new timestamp. This timestamp then gets up ...

What is the best way to transfer data from form input fields to a script with AJAX and jQuery?

Here is the current structure of my code. Main File: index.php <script type="text/javascript" src="jquery-1.4.2.js"></script> <script type="text/javascript" src="ajax.js"></script> <select id="dropdown_id"> <option valu ...

Updating JSON data in real time using JavaScript by manipulating MySQL database entries

My database has a mysql structure consisting of the columns ID, NAME, and TYPE. The data is then converted into a JSON format as shown below: [ {id: "1", name: "Snatch", type: "crime"}, {id: "2", name: "Witches of Eastwick", type: "comedy"}, { ...

Tips for preventing issues with Javascript latency causing flash out during page loading in Chrome

When building a page with Vue.js or any other Javascript, the issue of temporary flash during loading on Chrome due to constructing latency can be quite frustrating. This delay is not caused by asynchronous ajax requests, but rather the processing involv ...

Show or hide a div through two variables that toggle between different states

It's possible that I'm not fully awake, so missing the obvious is a possibility. However, I have 2 variables that determine whether a div has a specific class or not. The class functions more like a toggle; so the following conditions should tri ...

Utilize a generic data type for a property that can accept values of type 'number', 'string', or 'undefined'

This query involves React code but pertains to typescript rather than react. To simplify, I have a component called MyList which accepts a single generic type argument passed to the props type. The generic type represents an object that will be used to c ...

The functionality of the back button in a JavaScript website only allows users to navigate through their browsing

I'm currently experiencing an issue with the back navigation button on my one-page website. When I load a new page, I use the following code snippet: displayPage = function (page, json) { var stateObj = { "page": page, 'json': j ...

Loop within a promise results in undefined

Within my application, there is a function that returns a promise. Inside this function, I wait for an image in the DOM to become available and then extract that element to generate base64 data from it. getCodesOfOneMerchant(merchantDataEntry: MerchantData ...

Is gulp.dest set to match the current file?

I'm having trouble directing my compiled .css file to the same directory as its original .scss version. gulp.task('sass', function() { return gulp.src([ appDir + '/*.scss', appDir + '/**/*. ...

TypeScript is unable to recognize files with the extension *.vue

Can someone assist me with an issue I'm facing in Vue where it's not detecting my Single File Components? Error message: ERROR in ./src/App.vue (./node_modules/ts-loader!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/Ap ...