Getting star ratings from the "rating" field in an array of objects using JavaScript

I am dealing with an array of objects that looks like this:

var test_data = [    
                {
                    "id" : "Test01", //Must be a string form ID
                    "test_info"  : "This is the test information",
                    "test_rating" : 5
                },
                {
                    "id" : "Test02", //Must be a string form ID
                    "test_info"  : "This is the test information",
                    "test_rating" : 2
                }

Currently, I am using the following code to populate an unordered list (but it only displays the id)

fieldOutputId.forEach(function(id) {
    $("#idList").append('<li><a href="#">' + id +" "+ "</a></li>"); 
});

I want to display stars and the value of test_rating stored in

fieldOutputRating</code as shown in this picture (stars represented by red text)</p>

<p>Reference Image :<a href="https://i.sstatic.net/Y0eBj.png" rel="nofollow noreferrer"></a></p>

<p><strong>-----EDIT-----</strong></p>

<p>Thanks to @ChrisG, we have achieved displaying id & test_rating inline:</p>

<pre><code>test_data.forEach(function(item) { $("#idList").append('<li><a href="#">' + item.id+ '</a><div class="fa fa-star">'+ item.test_rating+ "</div></li>"); })

Using the above code successfully displays the stars inline using font-awesome library with class="fa fa-star

This is the current output:

https://i.sstatic.net/7uzJl.png

Although the test_rating is displayed, the stars are not. Any help on how to fix this issue would be greatly appreciated.

Answer №1

Is this what you had in mind?

const example_data = [    
  {
    "id" : "Example01",
    "example_info" : "This is the example information",
    "example_rating" : 5
  },
  {
    "id" : "Example02",
    "example_info" : "This is the example information",
    "example_rating" : 2
  }
];

example_data.forEach(({id, example_rating}) => {
  $("#idList").append(`<li><a href="#">${id}</a> ${'*'.repeat(example_rating)}</li>`);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="idList" />

Answer №2

To create a visual representation of the star rating based on user input, follow the example below:

test_data.forEach(function(data) {
    let rating_str = '';
    for (let i = 0; i < data.rating; i++) rating_str += '*';
    $("#idList").append('<li><a href="#">' + data.id +" "+ "</a><span>" + rating_str + "</span></li>"); 
});

If you prefer to use an image for your 'star' instead of just '*', modify the code like this:

rating_str += '<img src="..." />'

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

A guide on how to split the Bootstrap 4 card-body class into distinct columns

I currently have a bootstrap 4 card layout that looks like this: <div class="card-body"> <img src="{{asset('images/yimage.jpg')}}" alt="..." class="rounded-circle"> <p>This is ...

Optimizing File Transfers and Streaming Using Next.js and CDN Integration

As I work on developing a download system for large files on my website using Next.js and hosting the files on a CDN, I face the challenge of downloading multiple files from the CDN, creating a zip archive, and sending it to the client. Currently, I have i ...

Getting the Pesky JQuery Switcher to Actually Function

I am currently learning Jquery effects to enhance the interactivity of my websites. I have set up a practice page with the following structure: <article><a class="front-fire" href="1"></a></article> <article><a class="fron ...

The function document.getElementById is unable to retrieve the input value

I am attempting to extract the content of an input using document.getElementById. It successfully retrieves other values, but it fails specifically for this one. let title_input = document.getElementById('HomeworkTitle').value; is what I'm ...

Tips for creating a responsive and centered scrollable horizontal gallery in Bootstrap, starting with the first of three images

Currently working on my portfolio and have incorporated a horizontally scrolling gallery featuring 3 macbook screenshots of my personal projects. My bootstrap skills are still developing, so any assistance would be greatly appreciated. Primarily, I am aim ...

Using jQuery and Ajax to populate a dropdown menu with options

I'm currently working on an ajax call function that successfully fills a drop-down list with data from a specific URL. However, I am looking to modify the function so that it can receive variables in order to populate the drop-down list dynamically. ...

How can I make the cssRenderer layer element transparent so that the webglRenderer layer is visible beneath it in Three.js?

A test is being conducted on a cssRenderer that is running a scene directly in front of a webglRender. This setup allows both to run together, creating the illusion of including html dom elements (div and text) in webgl. The goal is to make the textbox ba ...

The functionality of Expo FileSystem.writeAsStringAsync does not resemble that of a Promise

While using the Expo.writeAsStringAsync() function, I encountered a situation where it took different times to write files of different sizes, which is expected. However, I noticed that there is no way to determine when the writing process has finished bec ...

What is causing the width discrepancy in my header section on mobile devices?

Help needed with website responsiveness issue! The site works fine on most screen sizes, but when it reaches around 414px in width, the intro section becomes too wide for the screen. Any ideas on what could be causing this problem? html: <nav id="m ...

Utilizing a combination of CSS and JavaScript, the traffic light can be altered to change based on

**I stumbled upon this online code snippet where a timer is controlled in CSS. I'm trying to figure out how to control it with JavaScript, but all my attempts have failed so far. Is there anyone who can help me solve this issue? What I'm attempti ...

Exploring the best practices for organizing logic within Node.js Express routes

I'm currently utilizing the https://github.com/diegohaz/rest/ boilerplate, but I am unsure about the best practice for implementing logic such as QR code generation and additional validation. My initial thought was to include validation and password ...

karma plugin dependencies could not be located

Every time I execute karma start, the following issues arise: C:\devl\JS\myProject>karma start 06 09 2015 11:30:19.133:WARN [plugin]: Cannot find plugin "karma-chrome-launcher". Did you forget to install it ? npm install karma-chrome ...

Displaying a document file on a webpage hosted by a raspberry pi

My Raspberry Pi hosts a local website that does not require an internet connection. I want the webpage to display text from a large file line by line as users access it. For example, if the text file contains: Hello How are You doing Today? The brow ...

Steps for displaying the contents of a file from Firebase storage on a React component

I uploaded a file to Firebase storage, and I want my app to be able to access and display the contents of that file within my class component div. Currently, when I try to access the file, it just opens in a new tab instead. class ScanResult extends Comp ...

Difficulty establishing a connection between NodeJS and Google Drive API

I am currently facing a challenge in my NodeJS application where I'm attempting to set up a gallery page. Despite having all the necessary configurations and connections with Google Drive API, something seems amiss when accessing the /gallery route. T ...

Azure Function App experiencing unexpected delay in async operations

I'm currently working with the Azure storage SDK for node in order to create a Table in Table Store if it doesn't already exist. After running the following code, I receive a 200 response with no content. However, the table is successfully creat ...

Tips for ensuring the correct size of images and their captions within a figure element

I'm struggling with the CSS for an image inside a figure. Here is the HTML: #content figure { display: inline-block; border: 1px solid #333333; height: 200px; margin: 10px; } #content img { height: 180px; background-size: auto 100%; b ...

Determining the height of the first element in jQuery

I am dealing with multiple elements that share the same class but have different heights. The class 'xyz' is only for styling borders, as shown below: <div class='xyz'></div> //1st element height=10px <div class='xy ...

What is the proper way to declare a Type for a JSX attribute in Google AMP that utilizes square brackets?

When utilizing AMP's binding feature, you must apply specific attributes that encapsulate an element's property with square brackets and connect it to an expression. An example from AMP is shown below: <p [text]="'Hello ' + foo"> ...

Using Regular Expressions as an Alternative to Conditionals

My knowledge of RegEx is limited, but I'm trying to make the following expression work with Javascript/Typescript: /^({)?(?(1)|(\()?)[0-9A-F]{8}(-)?([0-9A-F]{4}(?(3)-)){3}[0-9A-F]{12}(?(1)}|(?(2)\)))$/i This RegEx is used to check if a str ...