What is the best way to transfer JavaScript data to HTML?

I'm having trouble displaying my JSON data in HTML. I converted the JSON data into variables and created additional variables to access specific elements within the JSON data. However, when trying to pass this data to HTML using document.getElementById, only the last element is being printed as the Id is unique. Can someone please assist me with a solution for displaying JavaScript variable data in HTML?

var obj = [{
    "client_msg_id": "3a223f8d-b5aa-4c9c-9b63-045ec6f90b58",
    "type": "message",
    "text": "hey there",
    "source_team": "TN4AF0V5W",
    "team": "TN4AF0V5W",
    "user_profile": {
      "real_name": "marvelmohinish99",
      "team": "TN4AF0V5W"
    }
  },
  {
    "client_msg_id": "3a223f8d-b5aa-4c9c-9b63-045ec6f90b58",
    "type": "message",
    "text": "welcome",
    "source_team": "TN4AF0V5W",
    "team": "TN4AF0V5W",
    "user_profile": {
      "real_name": "marvelmohinish99",
      "team": "TN4AF0V5W"
    }
  },
  {
    "client_msg_id": "3a223f8d-b5aa-4c9c-9b63-045ec6f90b58",
    "type": "message",
    "text": "Help me",
    "source_team": "TN4AF0V5W",
    "team": "TN4AF0V5W",
    "user_profile": {
      "real_name": "marvelmohinish99",
      "team": "TN4AF0V5W"
    }
  }
];

for (var i in obj) {
  var type = obj[i].type;

  var text = obj[i].text;

  var source_team = obj[i].source_team;

  var user_profile = obj[i].user_profile;

  var real_name = user_profile.real_name;


  console.log(source_team + " : " + real_name);

  console.log(text);

  document.getElementsByClassName('a1').innerHTML = text;
}
<h2>Convert a string written in JSON format, into a JavaScript object.</h2>

<p id="output"></p>
<p class="a1"></p>

Answer №1

Below is a demonstration of how you can organize this data in a basic table layout. Typically, the .innerHTML or .innerText properties are utilized to dynamically insert elements into your HTML structure:

var obj = [{
    "client_msg_id": "3a223f8d-b5aa-4c9c-9b63-045ec6f90b58",
    "type": "message",
    "text": "hey there",
    "source_team": "TN4AF0V5W",
    "team": "TN4AF0V5W",
    "user_profile": {
      "real_name": "marvelmohinish99",
      "team": "TN4AF0V5W"
    }
  }, 
  // Additional objects...
];

for (var i in obj) {
  var type = obj[i].type;
  var text = obj[i].text;
  var source_team = obj[i].source_team;
  var user_profile = obj[i].user_profile;
  var real_name = user_profile.real_name;

  var message = document.createElement("tr");
  message.innerHTML =
  "<td>" + type +
    "</td><td>" + text +
    "</td><td>" + source_team +
    "</td><td>" + user_profile +
    "</td><td>" + real_name + "</td>";

  document.getElementsByClassName('a1')[0].append(message);

}
table, th, td{
  border: 1px solid black;
}
<p id="output"></p>
<table class="a1">
  <th>Type</th>
  <th>Text</th>
  <th>Source Team</th>
  <th>User Profile</th>
  <th>Real Name</th>
</table>

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

Check if a JSON object is encompassed within another JSON object

Recently, I was faced with the task of creating a method to determine whether the first JSON object is contained within the second JSON object. After much thought, I developed a rather straightforward method: public static partial class JsonOperations { ...

A tool for viewing JSON files and retrieving specific data by using a key within the JSON structure

Is there an online tool available that can extract specific data from a JSON array of objects? Take this JSON array for example: { "results": [ { "createdAt": "2015-09-02T02:03:55.765Z", "name": "Clush", "score": 15, " ...

Receiving JSON output twice

I am currently working with CodeIgniter and facing an issue with my form fields, which are Employee_name, fromDate, and endDate. I am using AJAX to send this data without sharing the actual code. The problem arises when retrieving and displaying records fr ...

The data from the Ajax request failed to display in the table

JavaScript Code</p> $(function (){ $.ajax({ type : 'GET', url : 'order/orders.json', dataType : 'JSON', success: function(data) { /*var trHTML = ''; $.each(orders, function (i, it ...

Typescript Angular filters stop functioning properly post minification

I developed an angular filter using TypeScript that was functioning properly until I decided to minify the source code. Below is the original filter: module App.Test { export interface IGroupingFilter extends ng.IFilterService { (name:"group ...

Using local storage with github sites can lead to some unexpected and peculiar behavior

Currently, I am working on a simple clicker game using HTML and JavaScript. To store the variables money and taxCollecters, I have implemented local storage. However, I am encountering strange issues when trying to use the save and load buttons on the Gi ...

Is CakePHP unable to handle multiple Ajax requests simultaneously?

After multiple rounds of editing this post, I keep uncovering new information through testing and debugging. Here is my current situation: I have a method thinker that takes a significant amount of time to process. To address this, I have decided to call ...

Problem encountered with sorting single and double digit numbers using NSSortDescriptor

I recently encountered a challenge while sorting my array based on experience. The code I used for sorting looked like this: sortexp = [NSSortDescriptor sortDescriptorWithKey: @"Experience" ascending:YES]; arrData = [arrData sortedArrayUsingDescriptors: ...

How to reference a variable name within a JSON selector in AngularJS

I am working on a table using angularjs where I need to iterate through an array to display specific headers from a json object. The header displays correctly, but the issue arises when trying to utilize a variable from my nested ng-repeat as a json select ...

Retrieving a JSON array and showcasing the outcomes from it

I am attempting to display data on a page that is retrieved from an API call, specifically related to bitcoin payments. My goal is to show confirmation details, amounts, and other information for orders paid with bitcoins. Here is a sample URL which provi ...

No output being generated by form

I've put in a lot of effort to recreate the files so that a message would pop up when information is entered into the username and password fields. Unfortunately, I'm facing an issue where the message display isn't working as intended. Chec ...

Refresh the module.exports in a Mocha unit testing script

I am currently learning about nodejs and mocha, and I have developed a JavaScript program to display the files in a folder along with a unit test case using the mocha and chai framework. My goal here is to reset the object set in module.export before each ...

JavaScript problem indicating an error that is not a function

Recently, I've delved into the world of JavaScript and am currently exploring JavaScript patterns. I grasp the concepts well but struggle with calling functions that are already in an object. var productValues = 0; var cart = function(){ this. ...

Restrict the quantity of items retrieved from an AJAX response

An AJAX call has returned a response consisting of a list of <a> elements: <a href="/1/">One</a> <a href="/2/">Two</a> <a href="/3/">Three</a> I am looking to select only the first n a elements from this response ...

Issue with Ext JS: The property 'substring' is being attempted to be read from an undefined value

Hey there! I'm trying to incorporate a grid panel into my view using Extjs 4.1.1, but I keep encountering an error in the browser console that says "Cannot read property 'substring' of undefined". Below is the JavaScript code snippet I am us ...

Is there a way to identify a visitor's country and automatically direct them to a relevant website?

Despite reading multiple answers, I am still unsure how to redirect my website's visitors based on their country. I have a basic understanding of HTML and JavaScript. Can someone kindly provide me with the code for this task? ...

Webpack in Vuejs does not have access to the keys defined in dev.env.js file

The framework utilized here is vuejs-webpack, with build and config files located here. No modifications have been made to these files. According to the information on Environment Variables, the keys specified in dev.env.js should be accessible during the ...

What is the most efficient method for sending query parameters through a URL in Vue.js with Axios?

My goal is to use Axios upon page load to retrieve a JSON object from the base URL. When a button is clicked, I want to append query parameters to the URL and fetch a different JSON object. For example, if the base URL is 'test.com', clicking the ...

How to manage the state when multiple forms are generated by clicking a button

I am currently working on a feature that allows users to add multiple addresses, with a limit of 3 additional addresses in addition to the default one that cannot be removed. For this specific case, each address consists of a street name and city. My cha ...

Trouble receiving a reply from the Angular controller

I'm a newcomer to AngularJS and I'm currently working on integrating AngularJS into one of my existing applications. Below is the provided HTML and JavaScript code: <!doctype html> <html ng-app="ldlApp"> <head> <script src= ...