Traversing an array of objects can result in an extraneous comma being displayed in the markup

View screenshot showing unwanted comma in output

Hello there, I'm currently working on a gold shop website and dealing with an array of product objects. When mapping through this array to display products on the main page, I've encountered an issue where an extra comma character appears in the output unnecessarily. Can someone assist me in resolving this problem? Feel free to check out the screenshots for reference.

const products = [
  {
    id: 1,
    title: 'Vintage Georgian Watch',
    prob: 583,
    weight: 19.74,
    price: 2100,
    img1: 'img/watchWm1.jpg',
    img2: 'img/watchWm.jpg',
    category: 'watch',
    gender: 'woman'
  },
  // Additional product objects go here...
];

// Code snippet for displaying all products on the Main Page
var productsOuterDiv = document.getElementById('productsOuterDiv');
const productsBox = products.map(product => `<div class='productDiv'>
      <div class='imgDiv'>
      <img src='${product.img1}' alt='${product.title}'>
      </div>
      <h6><strong>${product.title}</strong></h6>
      <p><strong>Weight:</strong> ${product.weight} grams</p>
      <p><strong>Sinj (Prob):</strong> ${product.prob}</p>
      <p><strong>Price:</strong> ${product.price} Lari</p>
      <button class='btn btn-details'>Details</button>
    </div>`);
productsOuterDiv.innerHTML = productsBox;

Answer №1

When you update the productsOuterDiv with productsBox using

productsOuterDiv.innerHTML = productsBox;
, it automatically converts the array elements to strings and separates them with commas. To prevent this, you can use the join method as shown below:

productsOuterDiv.innerHTML = productsBox.join('');

var items = [`<span>1</span>`,`<span>2</span>`,`<span>3</span>`];

document.getElementById("output1").innerHTML = items;
document.getElementById("output2").innerHTML = items.join("");
span{ border: 1px dashed #CCC; }
<div id="output1"></div>
<hr>
<div id="output2"></div>

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

How can I simulate a callback function that was not tested?

Currently experimenting with the method below: startScriptLoad(): void { const documentDefaultView = this.getDocumentDefaultView(); if (documentDefaultView) { const twitterData: ICourseContentElementEmbedTweetWidgetData = this.getTwitterWid ...

Angular 2 - Graphic Representation Tool for Visualizing Workflows and Processes - Resource Center

Looking for a library that can meet specific requirements related to diagram creation and rendering. We have explored jsplumbtoolkit, mermaid, and gojs, but none of these fully satisfy our needs. For example, we need the ability to dynamically change con ...

Is it possible to apply styles to javascript elements without relying on img class? Additionally, how can I incorporate an onclick button while maintaining a fully functional navigation bar?

My current project involves creating an interactive collage where users can click around and have pictures pop up at the clicked location. The functionality works as intended, but now I'm facing issues with the navigation bar not being clickable. Addi ...

retrieve a unique array that is not present in another array

Let's consider two arrays as an example: array1 = (2, 3, 4); array2 = (1, 2, 3, 4, 5); We need to find the values in array2 that are not present in array1. By doing this, we can create a new array named array3 which will include the following elemen ...

Rxjs: Making recursive HTTP requests with a condition-based approach

To obtain a list of records, I use the following command to retrieve a set number of records. For example, in the code snippet below, it fetches 100 records by passing the pageIndex value and increasing it with each request to get the next 100 records: thi ...

Error in AWS Cloud Development Kit: Cannot access properties of undefined while trying to read 'Parameters'

I am currently utilizing aws cdk 2.132.1 to implement a basic Lambda application. Within my project, there is one stack named AllStack.ts which acts as the parent stack for all other stacks (DynamoDB, SNS, SQS, StepFunction, etc.), here is an overview: im ...

Reactstrap: Is it necessary to enclose adjacent JSX elements within a wrapping tag?

While working on my React course project, I encountered an issue with my faux shopping website. The error message that keeps popping up is: Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...& ...

What is the best way to determine the height of a DIV element set to "auto"?

When setting a fixed height on a div using jQuery, such as $('div').height(200);, the value of $('div').height() will always be 200. This remains true even if the content within the div exceeds that height and overflow is hidden. Is th ...

Enhance your viewing experience with the Zoom feature that activates when

I recently noticed on that I am able to zoom/enlarge a photo by clicking on it. Is there a way for me to incorporate this feature without purchasing the entire theme? While I understand the theme is designed for purchase, I only need this specific functi ...

The absence of localStorage is causing an error: ReferenceError - localStorage is not defined within the Utils directory in nextjs

I've been trying to encrypt my localstorage data, and although it successfully encrypts, I'm encountering an error. Here's the code snippet (./src/utils/secureLocalStorage.js): import SecureStorage from 'secure-web-storage' import ...

.then function not functioning properly in Axios DELETE request in a React project

I am currently facing an issue with calling a function to update the array of notes after deleting a note from the database. The function causing the error is called deleteNote, and the function I intend to call within the .then promise is getNotes. Here i ...

Add a variable from a callback function in AJAX's success response

Is there a way to effectively utilize the variable in the appended message of the AJAX success call? http://codepen.io/anon/pen/fdBvn data['name'] = $('#goofy').val(); $.ajax({ url: '/api/1/email/test/', data: data, type ...

How can you proactively rebuild or update a particular page before the scheduled ISR time interval in Next.js?

When using NextJS in production mode with Incremental Static Regeneration, I have set an auto revalidate interval of 604800 seconds (7 days). However, there may be a need to update a specific page before that time limit has passed. Is there a way to rebui ...

Storing the array with the highest length in a temporary array using Javascript

I am currently working with two arrays that can be of equal length or one may be longer than the other. My goal is to determine the longest array if they are not equal in length, and then use this length to control a loop. $.ajax({ url: "/static/Dat ...

Tips for arranging various information into a unified column within an Antd Table

Is there a way to display multiple data elements in a single cell of an Ant Design table, as it currently only allows insertion of one data element? I am attempting to combine both the 'transactionType' and 'sourceNo' into a single cell ...

The error message "Uncaught ReferenceError: req is not defined with [email protected]" indicates that the variable

Discovered a helpful post that seems to address the problems. https://github.com/angular/angular-cli/issues/8359 I'm unsure about the steps to take next to resolve this issue. Can anyone clarify? Could you please advise on which version of Angular ...

Challenge with Filter Functionality when Activating Button

Can you help me implement a search filter using buttons with the Isotope Plugin? For example, entering a search value in an input field and then clicking a search button to display the search results. How can I achieve this using buttons? Below is the H ...

Stop MatDialog from closing automatically when clicked outside while there are unsaved changes

Is there a way to prevent closing when there are pending changes without success? this.dialogRef.beforeClosed().subscribe(() => { this.dialogRef.close(false); //some code logic //... }); The setting disableClose on MatDialog must remain as false ...

The setInterval function is malfunctioning

If I have the following function: function check(){ alert("Welcome"); } window.onload = check(); setInterval("check();", 5000); However, it is not working properly. Oddly enough, when I refresh the page, it works as intended. How can I resolve this i ...

Converting a TypeScript array into a generic array of a specific class

I am attempting to convert a JSON source array with all string values into another array of typed objects, but I keep encountering errors. How can I correct this code properly? Thank you. Error 1: There is an issue with converting type '({ Id: string ...