What methods can I implement to showcase random images in JavaScript using a JSON array value?

I am currently working on a fun avatar generator project. The challenge I'm facing is that each hairstyle consists of two parts (front and back), and when loaded randomly, the colors don't always match. To tackle this issue, I have organized the assets in a JSON file where they are grouped by colors. For instance, every ginger front hair, back hair, and eyebrows will always load together.
The tricky part now is figuring out how to implement these values in the random loading process, which has proved to be quite challenging for me as someone new to using JSON.

If anyone has any advice or leads on how to solve this problem, it would be greatly appreciated :-)

Below is a snippet of my JS script:

document.addEventListener("DOMContentLoaded", function() {
    // Code block
});

And here is an excerpt from my JSON file showing examples of hairstyles with corresponding colors:

    {
        "img": "/img/backhair/man/backhair1.png",
        "color": "blond"
    },

    {
        "img": "/img/backhair/man/backhair2.png",
        "color": "ginger"
    },

    {
        "img": "/img/backhair/man/backhair3.png",
        "color": "auburn"
    },

    {
        "img": "/img/backhair/man/backhair4.png",
        "color": "chestnut"
    },

    {
        "img": "/img/backhair/man/backhair5.png",
        "color": "black"
    },

Answer №1

Here's a simple method you can use:


    let backhair = get_random_image(20, 1); // making sure it matches
    let body = get_random_image(25, 1);
    let clothes = get_random_image(12, 1);
    let eyebrows = get_random_image(20, 1); // ensuring match
    let eyes = get_random_image(30, 1);
    let mouth = get_random_image(5, 1);
    let nose = get_random_image(4, 1);
    let fronthair = get_random_image(20, 1); // confirming match   

To simplify this process, randomize once and assign the same value to others:


    let matched = get_random_image(20, 1); // make sure it matches
    let backhair_nbr = matched;
    let body_nbr = get_random_image(25, 1);
    let clothes_nbr = get_random_image(12, 1);
    let eyebrows_nbr = matched;
    let eyes_nbr = get_random_image(30, 1);
    let mouth_nbr = get_random_image(5, 1);
    let nose_nbr = get_random_image(4, 1);
    let fronthair_nbr = matched;  

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

Despite successfully passing props into V-for, the output does not display the props as expected

I've been attempting to accomplish a straightforward task, but for some reason, it's not working and I can't figure out why. Within the parent component, App.vue, I have the following: data() { return { servers: [ { ...

Guide to specifying optional JSON fields in Golang structures?

In my programming practice, I have a preference for using pointers with primitive data types in my structs. By doing so, I ensure that when I use json.Marshal to convert them, any nil fields are represented as "field": null in the resulting JSON string. Ho ...

most effective method for establishing a relationship between a variable and its corresponding identification number

When retrieving results from a database with a simple PHP while loop, one of the data pieces includes a number that links to another table where the corresponding value is stored. While there are various ways to link this information and display the relate ...

Identifying Ctrl+V in VueJS: A Guide

Although I found the answers to this question, they were for jQuery and not suitable for my needs with vue.js. Currently, I have successfully implemented code to detect single character presses: export default { name: 'game', data () { ...

Enhancing URLs with jQuery/AJAX: A Comprehensive Guide to Adding Parameters

Whenever I try to use the get method on an HTML form, the submitted data automatically appears in the URL. You can see what I mean here. Interestingly, when attempting to achieve the same result with JQuery and AJAX using the get method, the data doesn&apo ...

Find the frequency of a specific string within a JSON array

My current task involves working with a stringified array: JSON.stringify(arr) = [{"x":9.308,"y":6.576,"color":"yellow","restitution":0.2,"type":"static","radius":1,"shape":"square","width":0.25,"height":0.25},{"x":9.42,"y":7.488,"color":"yellow","resti ...

Change the name of a file to a name chosen by the user while uploading it to an

I'm a beginner when it comes to node.js and I'm facing an issue that I couldn't find a solution for despite looking into various related topics. My problem involves using Node.js on the server side to upload a file and rename it based on a ...

Why Does React Material-UI Switch Styling Keep Changing Sporadically?

Currently, I am trying to integrate a switch component from MUI into my code. Strangely enough, upon the initial page load, the switch appears exactly as it should - identical to the one displayed on the MUI site. However, upon reloading the page, it under ...

Guide on utilizing JSON data sent through Express res.render in a public JavaScript file

Thank you in advance for your assistance. I have a question that has been on my mind and it seems quite straightforward. When making an app.get request, I am fetching data from an external API using Express, and then sending both the JSON data and a Jade ...

What is the best way to save array information in Laravel?

I am encountering issues while trying to save data from another table in Laravel. As a newcomer to the framework, I could use some guidance. If anyone has experience with this, please lend me your assistance. The setup involves two tables: external_event ...

Using Python to validate JSON keys and values

I'm currently working on developing a Python code that takes a JSON file as input. This JSON file can contain various data structures such as dictionaries and lists. The main goal of my program is to print out the keys present in the JSON file. Howeve ...

Tips for creating a vertical drawer using jQuery and CSS

Hello, I am currently working on developing a drawer component using Ember.js. If you want to view the progress so far, feel free to check out this jsbin http://jsbin.com/wulija/8/edit My goal is to have the drawer look like the following initially: +--- ...

The PHP JSON data is not being correctly parsed by AJAX, despite the JSON being properly formatted

I have recently taken on the task of converting a legacy Classic ASP website to PHP. The original site had pages where the response content type was set to "application/json" and it would serve responses in the format {"R":1}, which all worked perfectly. ...

The DOMException occurred when attempting to run the 'querySelector' function on the 'Document' object

Currently, I am engaged in a project that was initiated with bootstrap version 4.3.1. I have a keen interest in both JavaScript and HTML coding. <a class="dropdown-item" href="{{ route('user.panel') }}"> User panel </a& ...

Start flicker issue in Vue 3 transition

I have created a carousel of divs that slide in and out of view on the screen. However, I am facing an issue where during the start of each transition, when a new div is rendered (i.e., the value of carousel_2 changes), it appears without the transition-en ...

Explaining the implementation of JQuery's onload event and its impact on reducing dependencies

Contained within a table is some data https://i.stack.imgur.com/gQyJQ.png Upon clicking the edit button, I am able to modify the information in that specific row. The Menu Category and Menu are populated through Dependent dropdowns. https://i.stack.imgur ...

Generating a Transform stream with ExcelJS to produce xlsx files

Currently, I am utilizing the ExcelJS module and creating a wrapper to suit my specific needs. This wrapper implements the Transform Stream API, and surprisingly, the node version being used is 0.10.40. The ExcelJS module offers a stream API, and based on ...

Retrieving Information from MongoDB Collection with Paginated Results in Universal Sorted Sequence

I'm in the process of working on a project that involves a MongoDB collection called words, which holds a variety of words. My objective is to retrieve these words in a paginated manner while ensuring they are globally sorted in lexicographical order. ...

When navigating back, the Bootstrap Multistep Form breaks down

Tools I'm currently utilizing: HTML, CSS, Javascript, Bootstrap 3 Library / Package in use: https://codepen.io/designify-me/pen/qrJWpG Hello there! I am attempting to customize a Codepen-based Bootstrap Multistep Form from the provided link abov ...

JavaScript: Working with Nested Callbacks and Retrieving MySQL Data

As I dive into the world of JavaScript server-side code, I find myself grappling with a common issue that many programmers face. In my previous experience with MySQL select queries in PHP, I would simply grab a result and loop through each row, performing ...