Exploring ways to loop through a JSON array and embed it into an HTML element

After the ajax request, the data returned is structured as follows:

Data = [
    ["18/02/2019", "A"],
    ["19/03/2019", "B"],
    ["21/05/2019", "C"],
]

The ajax request was successful and the data is stored in a variable named Data within a function.

success: function (Data) {
    for(i in Data) {
        // INSERT INTO HTML
    }
}

I have managed to iterate through Data and access each sublist as i. But I am struggling with how to display this in my HTML. I tried using

document.querySelectorAll('.Appointments').innerHTML = Data[i];
but it's not working.

The desired result should be displayed on the webpage, with each row having its own division:

18/02/2019 A
19/03/2019 B
21/05/2019 C

Being new to JSON, I would greatly appreciate a detailed explanation. Thank you.

Answer №1

Problem with the provided code:

document.querySelectorAll('.Appointments').innerHTML

The code above doesn't seem correct. querySelectorAll returns a collection of HTML elements with the class name "Appointments". However, a collection does not have the method innerHTML; only individual HTML elements possess this method. What was the intention behind this code?

It would be more suitable to target an element by its id.


for(i in Data) {
     // INSERT INTO HTML
}

The code above demonstrates an outdated method of looping through an array. There are now more efficient methods available for arrays. I suggest exploring the options provided.

I recommend utilizing Array#map and Array#join

Array#map:

Highly effective for transforming an array of data into an array of HTML strings.

The map() method creates a new array by executing a function on each element in the original array.

Array#join:

Perfect for converting an array of HTML strings into a single cohesive string.

The join() method joins array elements into a string using a chosen separator. If the array contains only one item, that item will be returned as is.

Solution:

Implement Array#map and Array#join. This approach is both efficient and easy to read.

This solution also involves destructuring (as seen in [date, label]).

const data = [
    ["18/02/2019", "A"],
    ["19/03/2019", "B"],
    ["21/05/2019", "C"],
];

document.getElementById("appointments")
.innerHTML = data
//convert array of data to array of HTML strings
.map(([date, label])=>(`<li>${date} : ${label}</li>`))
//combine array of HTML strings into a single HTML string
.join("");
<ul id="appointments"></ul>

Answer №2

To implement the functionality, you can utilize the code provided:

const data = [
  ["18/02/2019", "A"],
  ["19/03/2019", "B"],
  ["21/05/2019", "C"],
]
let li, ul;

function createList(data) {
  for (let i of data) {
    ul = document.getElementById("list");
    li = document.createElement("li");
    li.innerHTML = i[0] + " " + i[1];
    ul.appendChild(li);
  }
}

createList(data);
<ul id="list"></ul>

Answer №3

Using the document.querySelector method, the content of element with id 'a' is set to the result of mapping the Data array and joining each subarray with a space and adding a line break tag '<br/>'. 

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

Error: Element not found. Element with the specified XPath query '//button[normalize-space()='LOAD MORE']' could not be located

My current project involves creating a web scraper that is designed to continuously scroll down a page until it locates the "Load More" button and then clicks on it. However, I am encountering an issue where the program is unable to find the specified butt ...

Retrieve the total number of arrays from the API, rather than fetching the actual data

I'm attempting to retrieve the total number of arrays of validators (e.g. 1038) from a JSON file using the code below, but it doesn't seem to be working as expected. Can anyone spot what's wrong with my code? let data = fetch("https://avax. ...

Emphasize rows in the MUI-Datatables framework

A table was created using React.js and MUI-Datatables: import MUIDataTable from "mui-datatables"; const columns = ["Name", "Company", "City", "State"]; const data = [ ["Joe James", "Test Corp", "Yonkers", "NY"], ["John Walsh", "Test Corp", "Hartford", ...

When using AJAX POST requests, HTML links may become unresponsive

Scenario: Currently, I am developing a small-scale web application. The AJAX functionality is successfully sending data to create.php which then executes the necessary MySQL query. Upon completion of the AJAX request, a success message is appended to the d ...

Tips for avoiding an automatic slide up in a CSS menu

Is there a way to disable the automatic slide-up effect on my CSS menu when clicking a list item? I have tried using stop().slideup() function in my JavaScript code, but it doesn't seem to work. Additionally, I would like to highlight the selected lis ...

The presence of onChange?: (ValueType, ActionMeta) => void with OptionType is not compatible

After updating to version v2.4.2, I keep encountering an error from flow regarding react-select. It seems that I am passing the correct types to the handle change, which expects an array with objects + OptionType accepting any string [string]: any. Can som ...

"Identifying the exact number of keys in a JSON object using

Is there a key in the JSON data that may or may not exist? How can I determine the total number of occurrences of this key using jQuery? JSON : jasonData = [{"test":"sa3"},{"test":"4s"},{"acf":"1s"},{"test":"6s"}]; I need assistance with implementing th ...

The function signature '(newValue: DateRange<dateFns>) => void' does not match the expected type '(date: DateRange<unknown>, keyboardInputValue?: string | undefined) => void' as per TypeScript rules

I'm currently utilizing the MUI date range picker from https://mui.com/x/react-date-pickers/date-range-picker/. Here's my code snippet: <StaticDateRangePickerStyled displayStaticWrapperAs="desktop" value={valu ...

Using Regular Expressions in Javascript

I have gone through numerous posts with this title, but so far, none of them have addressed my specific query... My requirement is to utilize regex in the following format: "/^ user provided input $/i". The user can include the special regex character * e ...

Enhance your input text form with a stylish button using Bootstrap

This is the code snippet I am currently working on: <h2>Workout Selector</h1> <div class="form-group"> <label for="workout-name">Search by Keywords (Comma Separated):</label> <input ...

Transmitting JSON data using a Jquery AJAX request in PHP

I'm facing an issue passing a JSON array from a jQuery AJAX call to a PHP file and attempting to write the received data to a file. This is my code: var contacts = [{"address":[],"phone":[],"last_name":"abc","email":[{"address":"<a href="/cdn-cgi/ ...

Implementing a function in ReactJS that is activated by multiple buttons

Apologies for the unclear title. My issue revolves around having three different button tags, each of which should send a unique argument to the function selectSupplier(). However, no matter which button is clicked, only the last value ("ultramar") is be ...

Parsing a JSON data with JObject and LINQ techniques

Encountered a situation where I need to deserialize a large JSON object with specific conditions. { "fields": [ { "webhook": true, "associated_lookup": null, "json_type": "jsonobject& ...

What could be causing the oncomplete() method of OmniFaces Ajax utility to fail when triggered by the preRenderView event?

During my preRenderView event, I attempt to use the OmniFaces Ajax utility's oncomplete() method to run some javascript on the client side. However, after testing this feature, I noticed that the javascript is not actually being executed on the client ...

Tips for submitting a jQuery star rating:

I recently installed and added a plugin to one of my pages that transforms radio buttons into stars. While the form control works perfectly, I am facing an issue with submitting the form. The radio buttons are grouped together as stars but they do not subm ...

How can I stop columned-DIVs from wrapping on the webpage?

I am attempting to create floating/stacking boxes on the right side of the page as long as there is available space. I am close to achieving my desired layout, but the DIVs keep getting wrapped over each other, causing the headings to be lost. ...

Removing double quotes from a specific key value in a JSON object

I am working with a json file that has a specific structure. My aim is to eliminate the double quotes from the "value" in the source field. { tags:[ { name: "video", cssanimate: "flipInY", source: "{ mp4: &a ...

The functionality of JQuery Fancybox seems to be malfunctioning when attempting to integrate data retrieved from a

$.getJSON("/Home/AjaxBrowse", { page: p ? p : 1 }, function (data) { var output = ""; jQuery.each(data.users, function (key, value) { output += '<li>' ...

What is the best way to eliminate the space between two buttons in a table row or "column"?

Below is the code snippet that I am working with. I am trying to figure out a way to eliminate the space between the buttons both horizontally and vertically. Can someone guide me on how to achieve this? <%@page contentType="text/html" pageEncodin ...

Refresh the navigation bar on vuejs post-login

Creating a client login using Vue has been a challenge for me. My main component includes the navigation bar and the content rendering component. The navigation component checks if the user is logged in to display the buttons for guests and hide the button ...