Building a table from JSON using only JavaScript.orGenerate a

I am working with a dynamic Json containing multiple keys that may vary. Here is an example:

Var children = [{num = 6, name = me, phone = 7}, {num = 8, name = him, phone = 9}]

My goal is to create a table with the headers (num, name, phone)

Is there a way to achieve this using JavaScript without relying on JQuery?

Answer №1

var students = [{id: 1, name: 'John', grade: 85}, {id: 2, name: 'Emily', grade: 92}];

function addTableHeaders(table, keys) {
  var row = table.insertRow();
  for( var i = 0; i < keys.length; i++ ) {
    var cell = row.insertCell();
    cell.appendChild(document.createTextNode(keys[i]));
  }
}

var table = document.createElement('table');
for( var i = 0; i < students.length; i++ ) {

  var student = students[i];
  if(i === 0 ) {
    addTableHeaders(table, Object.keys(student));
  }
  var row = table.insertRow();
  Object.keys(student).forEach(function(k) {
    console.log(k);
    var cell = row.insertCell();
    cell.appendChild(document.createTextNode(student[k]));
  })
}

document.getElementById('classroom').appendChild(table);
<div id="classroom"></div>

Answer №2

Follow the steps below to generate a table using JSON data. First, you need to copy the provided JavaScript and HTML code.

Javascript

<script type="text/javascript">
function convertJsonToTable(jsonData) {
  var parsedJson = JSON.parse(jsonData);
  var columns = [];
  var tableHeader = "<thead><tr>";
  for (key in parsedJson[0]) {
    columns.push(key);
    tableHeader += "<th>" + key + "</th>";
  }
  tableHeader += "</tr></thead>";
  document.getElementById("tableID").innerHTML = tableHeader;
  var tableRows = '<tbody>';
  for (var i = 0; i < parsedJson.length; i++) {
    var rowData = parsedJson[i];
      var jsonRow = rowData;
      var row = "<tr>"
        for (data in rowData) {
          var value = rowData[data];
          if (value != null) {
            var stringValue = value.toString();
            var replaceStr = "<\\";
            row += "<td><p>" + stringValue.split('<').join('&lt;') + "</p></td>";
          } else {
            row += "<td><p>null</p></td>";
          }
        }
      row += "</tr>"
      tableRows += row;
  }
  tableRows += '</tbody>';
  document.getElementById("tableID").innerHTML += tableRows;
}
</script>

HTML

<table id="tableID" class="table"></table>

Call the Method

convertJsonToTable("YOUR_JSON");

Example

var jsonData = '[{ "name":"John", "age":30, "car":"BMW"},'+
'{ "name":"Wick", "age":50,"car":"DODGE" }]';

convertJsonToTable(jsonData);

Answer №3

fetch('https://jsonplaceholder.typicode.com/todos').then(response => response.json()).then(data => generateTable(data)).catch(error=>console.error(error))

const generateTable = (data) => {
  const tableData = data;
  
  const headerData = Object.keys(tableData[0]);
  
  const table = document.createElement('table');
  
  const tr = table.insertRow(-1);
 
  
  for(let i=0; i<headerData.length; i++){
    const th = document.createElement('th');
    th.innerHTML = headerData[i];
    tr.appendChild(th)
  }
  
  for(let i=0; i<tableData.length; i++){
    const newRow = table.insertRow(-1);
        const item = tableData[i];
    for(let key in item) {
        const td = document.createElement('td');
      td.innerHTML = item[key];
      newRow.appendChild(td);
    }
}
  
  document.body.appendChild(table);
}

Answer №4

Code Snippet in Javascript

var _table_ = document.createElement('table'),
    _tr_ = document.createElement('tr'),
    _th_ = document.createElement('th'),
    _td_ = document.createElement('td');

// Function to create an HTML table from JSON data fetched via a RESTful service.
 function buildHtmlTable(arr) {
     var table = _table_.cloneNode(false),
         columns = addAllColumnHeaders(arr, table);
     for (var i=0, maxi=arr.length; i < maxi; ++i) {
         var tr = _tr_.cloneNode(false);
         for (var j=0, maxj=columns.length; j < maxj ; ++j) {
             var td = _td_.cloneNode(false);
                 cellValue = arr[i][columns[j]];
             td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));
             tr.appendChild(td);
         }
         table.appendChild(tr);
     }
     return table;
 }

 // Adds a header row to the table and returns the set of columns by combining keys from all records.
 function addAllColumnHeaders(arr, table)
 {
     var columnSet = [],
         tr = _tr_.cloneNode(false);
     for (var i=0, l=arr.length; i < l; i++) {
         for (var key in arr[i]) {
             if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key)===-1) {
                 columnSet.push(key);
                 var th = _th_.cloneNode(false);
                 th.appendChild(document.createTextNode(key));
                 tr.appendChild(th);
             }
         }
     }
     table.appendChild(tr);
     return columnSet;
 }


document.body.appendChild(buildHtmlTable([
    {"num" : "6", "name" : "me", "phone" : "7"},
    {"num" : "8", "name" : "him", "phone" : "9"}
]));

Styling with CSS in the Code Snippet

  th, td {
      border: 1px solid;
  }
  th {
      font-weight : bold
  }

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

When attempting to use the search bar to filter in ReactJs, an error occurs: TypeError - Unable to access properties of undefined (specifically 'filter')

When I receive data from my JSON server on the console, everything looks good. But when I try to type something in order to filter it, an unhandled error occurs with the message: 1 of 1 Unhandled Error Unhandled Runtime Error: TypeError: Cannot read prop ...

Eliminate repetitive elements from an array using a specific merging algorithm

Here's a thought I have: If we have an array of objects like this: [ { "name": "Kirk", "count": 1 }, { "name": "Spock", "count": 1 }, { "name": "Kirk", "count": 1 } ] I would l ...

Is there a way to invoke a php function in javascript with the help of Ajax?

I'm a beginner in javascript and ajax, attempting to call a php function that retrieves a patient's age in a javascript file. Despite looking into solutions on this topic, I haven't been able to figure it out yet. Here is the content of the ...

Enabling Javascript's power-saving mode on web browsers

I created a JavaScript code to play music on various streaming platforms like Tidal, Spotify, Napster, etc., which changes tracks every x seconds. If the last song is playing, it loops back to the first song in the playlist since some websites lack this fe ...

Ways to redirect to a different page following a successful execution of a mutation in React-query

I am facing an issue where a memory leak warning appears when I redirect to another page after a mutation. Despite trying various methods, I have not been able to find a solution. The specific warning message is: Warning: Can't perform a React state ...

Unable to access attribute of instantiated class

I am relatively new to TypeScript and I recently encountered a problem that's stumping me. I'm working on setting up a REST API using Express. The setup involves a router that calls a controller, which in turn invokes a service method before ret ...

A Step-by-Step Guide to Successfully Clicking on a Checkbox Using Selenium and Python

Hello everyone, I'm facing an issue with clicking a checkbox. Here is the code for the checkbox: <label class="has-checkbox terms"><input name="order[terms]" type="hidden" value="0" /><input class="checkbox" type="checkbox" value=" ...

Resolution for Vue3: Understanding why a component instance's template ref cannot locate a defined function

LoginInfo.vue <script setup lang="ts"> import { rules } from './config/AccountConfig' import { reactive } from 'vue' import { ref } from 'vue'; import { ElForm } from 'element-plus'; const info = reac ...

Discover the method for storing multiple values in local storage using a dictionary with JavaScript

I have a scenario in my code where I need to update a value without storing a new one. Let's say I need to input values in the following format: { firstname:'kuldeep', lastname:- 'patel' } After entering the values, they g ...

Node.js offers a simple and effective way to redirect users to another page after they have

I am experiencing an issue when trying to redirect the client to the confirm page after a successful login process. I keep encountering some errors. view screenshot router.post('/sign_in', urlend, function(req, res) { var email = req.body.user ...

Is it recommended to use separate Controllers for each tab in Angular JS to load the pane?

Recently delving into the world of Angular JS and eagerly seeking expert advice and suggestions. Would it be advisable to use separate controllers for initializing each Tab to load the Pane content? Is assigning separate controllers a recommended approac ...

What causes the mounted hook in Vue to be triggered multiple times when used within a plugin or mixin?

How can I prevent repetitive behavior in my code? Is this a bug that needs fixing? Take a look at the plugin below: const globala = { install(Vue) { Vue.mixin({ mounted() { console.log('hi') } }) } } And here&apos ...

What could be causing the issue with lodash throttle not functioning correctly in the useWindowSize custom hook?

I'm attempting to implement a resize event with throttle, but I'm encountering an issue. To troubleshoot, I have tried the following: import {throttle} from 'lodash' export function useWindowSize() { const [windowSize, setWindowSize] ...

React: Implementing localStorage token addition in loginHandler function using State hook is not functioning as expected

I've implemented an AuthContextProvider in my React application to handle user authentication and logout functionality: import React, { useState } from "react"; import axios from "axios"; import { api } from "../api"; co ...

Which RxJS operators necessitate unsubscription?

It can be confusing to know which operators in RxJS must be unsubscribed from to prevent subscription leaks. Some, like forkJoin, complete automatically, while others, such as combineLatest, never complete. Is there a comprehensive list or guideline availa ...

Update the content within a div based on the selected option from a dropdown menu or

Is there a way to change the displayed text based on user input or selected option? By default, the text shown is "Aa Bb Cc Dd Ee...", but it can be changed by selecting different options. If text is typed into the input field, the displayed text will up ...

What is the best way to delete a property from an object in an array using Mongoose? This is crucial!

Doc - const array = [ { user: new ObjectId("627913922ae9a8cb7a368326"), name: 'Name1', balance: 0, _id: new ObjectId("627913a92ae9a8cb7a36832e") }, { user: new ObjectId("6278b20657cadb3b9a62a50e"), name: 'Name ...

The presence of the backslash character is noticed while running a query in GraphQL

I'm struggling to find a solution for removing the '' character. I've attempted different methods, but none have been successful. It seems like Postgres changes the JSON string in that way. ...

Ensuring the authenticity of a Node.js model through the utilization of

Recently, I've been working on developing a NodeJS application using JavaScript and MySQL. As the object I'm handling started to grow in complexity making it difficult to read, I received a recommendation to implement the builder pattern. In resp ...

Constructing a hierarchical tree structure using an array of objects that are initially flat

My goal is to create a hierarchical tree structure from a flat array: The original flat array looks like this: nodes = [ {id: 1, pid: 0, name: "kpittu"}, {id: 2, pid: 0, name: "news"}, {id: 3, pid: 0, name: "menu"}, {id: 4, pid: 3, name: ...