What's the best way to showcase array values in JavaScript?

I am facing an issue where I am trying to display all values from the array "categories", but I keep getting [object object] or undefined. The problem seems to be occurring in the code within the last lines of the if statement, specifically when I try to call the "categories" array which seems to be of Object type.

  const urlKeys = [...new URL(window.location.href).searchParams.keys()];

  let categories = [];

  let count = urlKeys.length;

  for (let i = 0; i < count - 1; i++) {
    categories.push({ type: paramsFromUrl.get('category' + i) })
  }  //This is where I populate the categories array

  if (urlKeys[0] === 'allCategories') {
    document.getElementById('notice').innerText = "All categories included: [" + categories + "]";
    return viewsjs.createRestaurantCards(filterjs.findRestaurantsByCategory(await restaurantsjs.loadRestaurantsJSON(), categories));
  } //The issue lies here

Answer №1

categories is an array containing objects. To convert it to a string, you can utilize JSON.stringify

"List of all categories: " + JSON.stringify(categories);

If you only wish to show the type and not the entire object:

"All categories included: [" + categories.map(obj => obj.type) + "]";

Answer №2

Combining an Array directly into a String is not possible; it operates differently. It appears that using the join() method is necessary. This method will produce another String that can then be successfully merged into your main string for display in the DOM:

document.getElementById('notice').innerText = "All categories included: [" + categories.join(", ") + "]";

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

Nodemon isn't functioning properly: nodemon isn't loading as expected

db.js const mongoose = require('mongoose'); const mongoURI = "mongodb://localhost:27017/?readPreference=primary&appname=MongoDB%20Compass&ssl=false"; const connectToMongoDb = ()=>{ mongoose.connect(mongoURI, ()=>{ ...

Kudos to the information provided in the table!

My JSON data is structured like this: { description : "Meeting Description" name : "Meeting name" owner : { name: "Creator Name", email: "Creator Name" } } I want to present the details in a table format as follows: Meeti ...

The issue with using useState on arrays is that it is not functioning properly with React Hooks

const [LatestNews, setLatestNews] = useState([]); useEffect(() => { async function fetchLatestData() { const result = await database.collection('latestnews').get(); result.docs.forEach(doc => ...

Verify the entered information in the input field and showcase it in the display box after pressing the ENTER key

I need to display selected values of a tree structure in a show box on the other side of the page using code. However, I also need to include HTML input boxes in some lines of the tree structure so that users can input data. The challenge is getting the in ...

Utilizing Directives for DOM Manipulation in AngularJS

At this moment, I have a functional Angular app that is working properly. However, I am currently performing DOM manipulation within my controller instead of utilizing directives as recommended. My concern is, how can I correctly implement this functionali ...

Interactive data table feature in React, transferring selected row data to a modal pop-up

I am currently developing an offline Progressive Web App (PWA) using ReactJS and have integrated the react-data-table-component, which has been very helpful so far. Within the table, I have implemented an onRowClicked function that triggers whenever a row ...

Implementing Shader Effects around Mouse using Three.js

Could someone please share tips on how to add a shader effect around the mouse area using Three.js? I'm inspired by the homepage of this website: I'm eager to explore some leads or examples. Thank you in advance! ...

Prevent the beforeunload dialog box from appearing

Looking for a solution that is compatible with all browsers and operating systems. Referring to this resource https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload This is what I have so far: window.addEventListener("beforeunload", function ( ...

What is causing the Jquery repeater to not trigger .keyup and .change events on items beyond the second one?

I noticed that the .keyup and .change events are only triggered in the first input field and not after I add a new item. Is there a way to make these events trigger when adding a new field? http://jsfiddle.net/q8pcoaxf/ $('.field').on(& ...

Tips for sending a parameter within a JavaScript confirm method?

I currently have the following code snippet in my file: <?php foreach($clients as $client): ?> <tr class="tableContent"> <td onclick="location.href='<?php echo site_url('clients/edit/'.$client->id ) ?>&ap ...

Preserving color output while executing commands in NodeJS

My Grunt task involves shelling out via node to run "composer install". var done = this.async(); var exec = require('child_process').exec; var composer = exec( 'php bin/composer.phar install', function(error, stdout, stderr) { ...

Can Child Component Changes in React Checkbox Cause Parent Node to Re-Renders?

Struggling with creating checkboxes for my project, I've spent an entire day on it without finding a solution. The issue involves a main checkbox that controls all child checkboxes. The desired functionality is to have the parent node's "allChec ...

The nested div within the ui-view element is failing to expand to the entire width of the window

I am facing a challenge in making a child div stretch to the entire width of the window, rather than just the width of its parent. I am incorporating AngularJS with UI-Router, and I'm not sure if that is causing the issue. Attached is a screenshot. ...

The Material UI Drawer stays closed despite the state being set to true

Currently, I am in the process of developing a WebApp utilizing React and Material UI. Despite following numerous tutorials on implementing the Drawer component and poring over the documentation, I am still struggling to grasp its functionality. Even thou ...

Node.js: Error - Module 'html' not found

Currently, I am utilizing Node.js and attempting to exclusively serve HTML files without any Jade or EJS engines. Below is the code for my entry point (index.js): var express = require('express'); var bodyParser = require('body-parser&apo ...

The problem arises when Angular's $interval function is not recognized

Despite the possibility of this being considered a duplicate, none of the related topics have provided a solution to my simple date count down directive: class Clock { constructor() { this.restrict = 'AC'; this.replace = true ...

Float and tap

Can someone assist me with my code? I have 4 identical divs like this one, and when I hover over a link, all the elements receive the same code. <div class="Person-team"> <div class="profile-pic-d"> <a cl ...

Utilizing a variable name as an object key in TypeScript

Can this be achieved? static readonly statusMapping: { [key in UploadStatus]: PopupMessageStatus } = { UploadStatus.COMPLETED : PopupMessageStatus.COMPLETED } UploadStatus is an enum with numeric values, where UploadStatus.COMPLETED = 0 p ...

Crafting dynamic objects with THREE.JS

I am working with a JSON configuration that looks like this: { shape:[ 'SphereGeometry', [7, 16, 16] ] } My goal is to load a model using the following code: new THREE[shape[0]].apply( this, shape[1] ) However, it seems that using "new" and " ...

Is utilizing getStaticProps the best approach for handling offline data in Next.js?

My current project in Next.js involves offline static data for the webpage content. I am using an array to store the data for later mapping. Do you recommend using getStaticProps in this scenario? For example, here is a snippet of my code: import { data } ...