How can JSON be used to present all the data in a table using JavaScript?

Having trouble displaying all the data in a table and need some assistance. Can someone please help me resolve this issue? Thank you in advance!

var obj=[
            {
                id : "01",
                name : "Bob",
                prof : "Soft Engg"
            },
            {
                id : "02",
                name : "George",
                prof : "Admin"
            },
            {
                id : "03",
                name : "Paul",
                prof : "Front End"
            }
        ];
    var x = document.createElement("table");
    x.setAttribute("id", "myTable");
    document.body.appendChild(x);

    var y = document.createElement("tr");
    y.setAttribute("id", "myTr");

    for(i=0; i<obj.length;i++) {
      document.getElementById("myTable").appendChild(y);  
      var z = document.createElement("td");
      var t = document.createTextNode(obj[i]["id"]);
      z.appendChild(t);
      document.getElementById("myTr").appendChild(z); 
    }

Check out the demo here

Answer №1

To ensure that you have all the data from your list of objects, it's important to include a row for each object along with cells for each attribute associated with that object (id, name, prof). Currently, you are only adding one row and then omitting

Would something like this work? https://jsfiddle.net/n3va9cme/

var table = document.createElement("table");
table.setAttribute("id", "myTable");
document.body.appendChild(table);

for(i=0; i<obj.length;i++) {
  var row = document.createElement('tr');
  table.appendChild(row);

  for (key in obj[i]) {
    var cell = document.createElement('td');
    row.appendChild(cell);
    cell.innerHTML = obj[i][key];
  } 
}

Answer №2

give this a shot


var fruits=[
    {
        id : "001",
        name : "apple",
        category : "fruit",
        color : "red"
    },
    {
        id : "002",
        name : "melon",
        category : "fruit",
        color : "green"
    },
    {
        id : "003",
        name : "banana",
        category : "fruit",
        color : "yellow"
    }
];
var table = document.createElement("table");
table.setAttribute("id", "myFruitTable");
document.body.appendChild(table);

var row = document.createElement("tr");
row.setAttribute("id", "myFruitRow");

for(i=0; i<fruits.length;i++) {

  document.getElementById("myFruitTable").appendChild(row);  

  var row = document.createElement("tr");
  row.setAttribute("id", "myFruitRow");
  var cell = document.createElement("td");
  var idText = document.createTextNode(fruits[i]["id"]);
  var nameText = document.createTextNode(fruits[i]["name"]);
  var categoryText = document.createTextNode(fruits[i]["category"]);
  var colorText = document.createTextNode(fruits[i]["color"]);

  cell.appendChild(idText);
  cell.appendChild(nameText);
  cell.appendChild(categoryText);
  cell.appendChild(colorText);
  row.appendChild(cell); 

  document.getElementById("myFruitRow").appendChild(row);
}

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

Guide on fixing a parent div's position for a specific duration using the scrollorama plugin

Currently, I am utilizing the "scrollorama" plugin to create a parallax effect on my website. I have a specific requirement where I need to fix the parent div of the animated elements for a certain duration and then release it to allow the next section of ...

MVC Controller and JavaScript Ajax Call necessitate authentication for communication

In my ASP.NET MVC application, I am utilizing AJAX calls from the Client Page using AngularJS service to perform CRUD operations through Controller Action methods. While I have implemented ASP.NET form authentication for my MVC Pages, I am now looking to ...

Tips for submitting AJAX information instead of traditional form data

I am trying to send a simple input field as JSON data to a web server that I have set up. Here is what I have tried so far: <html> <head> <script src="http://code.jquery.com/jquery-1.11.3.js"></script> <script> $(document).r ...

What is the significance of mapping transformations on objects within MongoDB?

I encountered an issue. Every time I try to create a map in MongoDB, for example a shop, guildID: id, ownerID: owner_id, _premium: 0, Moderation:{ auto:false, prefix:'k!', muter ...

Is it possible to divide searches into separate divs?

How can I display the results of my AJAX live search in different result divs for styling purposes? I want to style the results separately and have them appear one at a time. However, the current setup with 'element.style' is causing issues. Is ...

How can I remove a specific item from obj?

Is there a way to create a function called removeStar that removes the star key from an object and outputs it in the format shown by the expectedOutput variable? let input = { "p": { "pk1": "pv1", "pk2": "pv2", "c": { "*": { ...

Javascript is sometimes unable to access data created by an ajax script

My Jquery Ajax script generates an HTML table in a situation. Another script filters the table column by providing a dropdown with unique values in that specific column. The filter script works fine with static content on the HTML page but is unable to re ...

Employ the vue.js method within the click EventListener of another method

In my Vue.js script, I have a method that generates an element called 'lens'. Now, I want to include an EventListener that triggers another method when the lens element is clicked. The problem: I have attempted two different approaches to add ...

Having trouble with my PHP/AJAX code - the Ajax request to PHP isn't functioning correctly, causing the rows not

I am currently working on a PHP chat application and running into some issues with utilizing AJAX to fetch data from a MySQL database and display it within a designated div. Below are the snippets of my code: HTML <div id="chatbox"> <div cla ...

Tips for creating a personalized dialog box after logging in with React Admin based on the server's response

One of my requirements is to allow users to select a role during the login process. Once the user enters their username and password, the server will respond with the list of available roles. How can I implement a dialog where the user can choose a role fr ...

Is it possible to utilize Dictionaries (key, value) collections with JQuery?

Is jQuery capable of supporting a collection of Dictionaries which consists of keys and values? I am interested in organizing the following data into a structured format: [1, false] [2, true] [3, false] This structure should allow for adding, looking up ...

Can the process of rounding values enhance the speed of JSON communication during AJAX requests?

Considering how frequently I need to retrieve large amounts of data multiple times within seconds using the $ajax or jQuery.getJSON method, I am contemplating the idea of rounding long floating-point values (e.g. 1.23242342344...) to shorter versions. My ...

Having trouble converting an empty array to JSON when attempting to create a JSON Object from a String?

Currently, I am utilizing the Kotlin language along with the GSON library to generate/parse JSON. The string below represents a JSON object: val jsonString = "{ \"age\": 22, \"height\" : 1.8, \"profession\":\"Student&bso ...

How can I organize an array in JavaScript by date for presentation on a webpage?

Check out this code snippet: list.component.ts const data1 = [ { dateStart: "2020-02-14 00:00:01", name: 'Server1' }, { dateStart: "2020-02-13 14:00:01", name: 'Server1' }, ...

Unexpected issue on AngularJS application

Encountering issues with incorporating a controller into my page - each time I add it to a DOM element, an error is thrown. Here's the structure of my HTML page: <html data-ng-app="sportsStore"> <head> <title>Sports Sto ...

What is the reason behind the inability of this YouTube instant search script to enable fullscreen mode?

Looking to implement a Youtube instant search on my website, I came across this script that seems ideal for my needs. However, I'm facing an issue where the iframe is not displaying the allowfullscreen property. Can anyone assist with this problem? Th ...

How can Navbar values in a React application be dynamically updated depending on the user's login status?

As someone new to React, I am exploring the correct approach to building a Navbar that dynamically displays different links based on a user's login status. When a user logs in, a cookie loggedIn=true is set. In my Navbar component, I utilize window.se ...

Click the "Add to Cart" button to make a purchase

Recently, I've been working on modeling an add to cart feature using jQuery. However, I have encountered a small issue that I'm trying to troubleshoot. When I click the mybtn button, the model displays and functions correctly, but there seems to ...

Converting JSON Firebase URL into an Array

I am trying to fetch data from a Firebase link in the form of an array. The Firebase link I have is https://.firebaseio.com/users.json which contains the following JSON file: { "-KOIbPUxKWKMaIOuX1cR": { "email": "<a href="/cdn-cgi/l/email- ...

Uniqid in React fails to generate unique IDs

Currently working on creating my first react project and developing a todo list. I have incorporated the uniqid generator into my todo object, but it seems to be returning an empty id rather than a random one. Oddly enough, if I move the todo state outsi ...