Create table from Json pure javascript - javascript

I have a Json with multiple keys that can change, something like this:
Var children = [{num = 6, name = me, phone = 7}, {num = 8, name = him, phone = 9}]
And I want a table with the headers (num, name, phone)
How can I do it with only JavaScript? (No JQuery)

var children = [{num: 6, name: 'me', phone: 7}, {num: 8, name: 'him', phone: 9}];
function addHeaders(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 < children.length; i++ ) {
var child = children[i];
if(i === 0 ) {
addHeaders(table, Object.keys(child));
}
var row = table.insertRow();
Object.keys(child).forEach(function(k) {
console.log(k);
var cell = row.insertCell();
cell.appendChild(document.createTextNode(child[k]));
})
}
document.getElementById('container').appendChild(table);
<div id="container"></div>

The below method will draw a table based on json.
First Copy the javascript and html
javascript
<script type="text/javascript">
function jsonToTable(json) {
var parsejson=JSON.parse(json);
var columns=[];
var tablethread="<thead><tr>";
for (x in parsejson[0]) {
columns.push(x);
tablethread+="<th>"+x+"</th>";
}
tablethread+="</tr></thead>";
document.getElementById("tableID").innerHTML=tablethread;
var table_rows='<tbody>';
for (var i = 0; i < parsejson.length; i++) {
var x= parsejson[i];
var json2=x;
var row="<tr>"
for (d in x) {
var sty=x[d];
if (sty!=null) {
var st=sty.toString();
var reps='<\\';
row+="<td><p>"+st.split('<').join('<')+"</p></td>";
}
else {
row+="<td><p>null</p></td>";
}
}
row+="</tr>"
table_rows+=row;
}
table_rows+='</tbody>';
document.getElementById("tableID").innerHTML+=table_rows;
}
</script>
HTML
<table id="tableID" class="table"></table>
Now Call Method
jsonToTable("YOUR_JSON");
Example
var jsonstring = '[{ "name":"John", "age":30, "car":"BMW"},'+
'{ "name":"Wick", "age":50,"car":"DODGE" }]';
jsonToTable(jsonstring);

fetch('https://jsonplaceholder.typicode.com/todos').then(response => response.json()).then(data => createTable(data)).catch(error=>console.log(error))
const createTable = (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 tr = table.insertRow(-1);
const obj = tableData[i];
for(let key in obj) {
const td = document.createElement('td');
td.innerHTML = obj[key];
tr.appendChild(td);
}
}
document.body.appendChild(table);
}

Javascript
var _table_ = document.createElement('table'),
_tr_ = document.createElement('tr'),
_th_ = document.createElement('th'),
_td_ = document.createElement('td');
// Builds the HTML Table out of myList json data from Ivy 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.
// Need to do union of keys from all records as some records may not contain
// 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"}
]));
CSS
th, td {
border: 1px solid;
}
th {
font-weight : bold
}

Related

Use Laravel route in javascript?

I have a Laravel route returning a JSON, and I have a JS file that dynamically generates a table with the results in a JSON.
I just need to use this JSON in my JS table. That's all.
JS code (registroCarros should receive the value from the JSON, route or whatever)
function CreateTableFromJSON() {
var registroCarros = []
// EXTRAI VALOR PARA O HEADER HTML
var col = [];
for (var i = 0; i < registroCarros.length; i++) {
for (var key in registroCarros[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE TABLE
var table = document.createElement("table");
table.id = 'myTable';
var tr = table.insertRow(-1); //ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); //HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
for (var i = 0; i < col.length; i++) {
var td1 = document.getElementsByTagName("tr"); //HEADER.
td1.id="teste;"
}
// ADD JSON IN TABLE AS ROWS.
for (var i = 0; i < registroCarros.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = registroCarros[i][col[j]];
}
}
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
My Controller (dbtest is a function in my model that have the SELECT im using):
public function returnJSON()
{
$teste = new user();
return response()->json(($teste->dbtest()));
}
and my route:
Route::get('returnJSON', 'App\Http\Controllers\Controller#returnJSON', ['names' => 'returnJSON']);
all I need is to use this route in my JavaScript.
Your Controller
public function returnJSON()
{
$teste = new user();
return response()->json($teste->dbtest());
}
Then your Route should look like this:
Route::get(
'returnJSON', // URL
'App\Http\Controllers\Controller#returnJSON' // Controller
)->name('returnJSON'); // Route name
Then finally in your blade file (JS code), you can use it as:
// behind any event (e.g. button click or value change etc.)
fetch("{{ route('returnJSON') }}") // This is the route name given in your route
// OR fetch("{{ url('returnJSON') }}") // and this is the URL (either can be used)
.then(res => res.json())
.then(data => CreateTableFromJSON(data));
/* đź”´REMEMBER */
// Your "CreateTableFromJSON" function must require an argument
// so that it can take the response (returned JSON) in it
function CreateTableFromJSON(registroCarros = []) {
// EXTRAI VALOR PARA O HEADER HTML
var col = [];
for (var i = 0; i < registroCarros.length; i++) {
for (var key in registroCarros[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE TABLE
var table = document.createElement("table");
table.id = 'myTable';
var tr = table.insertRow(-1); //ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); //HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
for (var i = 0; i < col.length; i++) {
var td1 = document.getElementsByTagName("tr"); //HEADER.
td1.id="teste;"
}
// ADD JSON IN TABLE AS ROWS.
for (var i = 0; i < registroCarros.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = registroCarros[i][col[j]];
}
}
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
NOTE
This JS code must be in your blade file otherwise you have to put exact URL in fetch, like: fetch('xyz.com/returnJSON')
Also verify if the controller & model is working fine and you're gettting proper data. You can do it in:
either Controller:
public function returnJSON()
{
$teste = new user();
$data = $teste->dbtest();
dd($data); // HERE
return response()->json($data);
}
or JS (in beginning of 'CreateTableFromJSON' function):
function CreateTableFromJSON(registroCarros = []) {
console.log(registroCarros); // HERE
...
}
Try this:
fetch('{{ route('returnJSON') }}')
.then((res) => res.json())
.then( data => CreateTableFromJSON(data))
And remove the empty array inside the function
function CreateTableFromJSON(registroCarros) {
//var registroCarros = [] remove this line
Change route:
Route::get('returnJSON', 'App\Http\Controllers\Controller#returnJSON')->name('returnJSON');
So, if I understand your code properly, the missing piece is just the question how you fetch remote data. This is how you do it:
fetch('returnJSON')
.then((res) => res.json())
.then(CreateTableFromJSON)
function CreateTableFromJSON(registroCarros) {
// ...

When create checkbox in JavaScript got [object HTMLInputElement]

This is my code
data = [{
name: 'Yemen',
code: 'YE'
},
{
name: 'Zambia',
code: 'ZM'
},
{
name: 'Zimbabwe',
code: 'ZW'
}
];
function addKeyValue(obj, key, data) {
obj[key] = data;
}
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
checkbox.name = "key";
checkbox.id = "id";
newinfo = data.map(function(person) {
return addKeyValue(person, 'checkbox', (checkbox)); });
var columnHeadings = Object.keys(data[0]);
var columnCount = columnHeadings.length;
var rowCount = data.length;
var table = document.createElement('table');
document.getElementById("data-list").appendChild(table);
var header = table.createTHead();
var row = header.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement('th');
headerCell.innerText = columnHeadings[i].toUpperCase();
row.appendChild(headerCell);
}
var tBody = document.createElement('tbody');
table.appendChild(tBody);
for (var i = 0; i < rowCount; i++) { // each row
var checkbox = document.createElement('input');
row = tBody.insertRow(-1);
for (var j = 0; j < columnCount; j++) { // each column
var cell = row.insertCell(-1);
cell.setAttribute('data-label', columnHeadings[j].toUpperCase());
var obj = data[i];
cell.innerText = obj[columnHeadings[j]];
}
}
In a tabular format I do have to get checkboxes with the json data. So firstly I have defined my json and then I have append checkboxes for each row.I am planning to add check boxes in every json object. But in my final output it is giving [object HTMLInputElement] instead of a checkbox.
You are adding the element object to your newinfo array, if you want the html for it you need to add it to the dom which it looks like you want to do at some point later in your code, to do this you would for example do document.body.appendChild(checkbox) if you wanted to add the checkbox to body.

Why do I get “undefined” in the table in my Firebase app?

I'm trying to create an app that retrieves data from Firebase and show it in a table using JavaScript. The problem is that it’s showing me “undefined” in the app and in the console and when I try to print the values directly from the functions they contain a value, so can anyone please help me with this?
This is my code:
function doSomething() {
var something = firebase.database().ref('*****');
//comment selection
something.on('value', function gotData(data) {
var values = data.val();
var keys = Object.keys(values);
var i = 0;
while (i < keys.length) {
var k = keys[i];
var comments = values[k].comment;
var idU = values[k].id;
var idS = values[k].idservice;
var nom = getuser(idU);
var service = getservice(idS);
var tr = document.createElement('tr');
var td = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
var t = document.createTextNode(i + ':' + comments);
var t2 = document.createTextNode(nom);
var t3 = document.createTextNode(service);
td.appendChild(t);
td2.appendChild(t2);
td3.appendChild(t3);
tr.appendChild(td);
tr.appendChild(td2);
tr.appendChild(td3);
document.getElementById("commentsection").appendChild(tr);
i++;
}
}, errData);
}
function getuser(IdU) {
var users = firebase.database().ref('******');
users.on('value', function getData(data) {
var values = data.val();
var keys = Object.keys(values);
var j = 0;
while (j < keys.length) {
var k = keys[j];
if (k === IdU) {
var name = values[k].nom;
console.log(name);
return name;
break;
} else {
console.log('not found');
break;
}
j++;
}
}, errData);
}
function getservice(IdS) {
var service = firebase.database().ref('******');
service.on('value', function getData(data) {
var values = data.val();
var keys = Object.keys(values);
var s = 0;
while (s < keys.length) {
var k = keys[s];
if (k === IdS) {
var nomservice = values[k].nomservice
console.log(nomservice);
return nomservice;
break;
} else {
return false;
}
s++;
}
}, errData);
}
function errData(err) {
console.log('error!');
console.log(err);
}
This is a screenshot for what I get:

Filter user input to display JSON data into a table from XMLHttpRequest?

I'm a beginner in JS and I'm unfortunately stuck on how to display the information that will be filtered by what a user puts in the input. Right now I have a table that will display the JSON info but I would like to filter like a letter or full name like "Trump", which will then will display a table of results. How would I combine the results that are filtered to make it into a table with the code I have?
The HTML
<form>
<label for="name">Name:</label>
<input id='input' placeholder="President Name" type="text">
<button onclick="loadPresidents()" type="button">Search for Presidents</button> <button type="button">Clear</button>
<div id="presidentialTable"></div>
</form>
The JS
function loadPresidents() {
"use strict";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
var data = this.responseText,
jsonResponse = JSON.parse(data),
table = document.createElement('table');
table.setAttribute('class', 'history');
var properties = ['number', 'name', 'date', 'took_office', 'left_office'];
var capitalize = function (s) {
return s.charAt(0).toUpperCase() + s.slice(1);
};
function filterResults() {
var input = document.getElementById('input').value;
var resultsFiltered = jsonResponse.filter(function(historicalData) {
return historicalData.indexOf(input) != -1;
});
var result = '';
resultsFiltered.map(function(a) {
result += a + '<br/>';
});
}
var tr = document.createElement('tr');
for (var i = 0; i < properties.length; i++) {
var th = document.createElement('th');
th.appendChild(document.createTextNode(capitalize(properties[i])));
tr.appendChild(th);
}
table.appendChild(tr);
var tr, row;
for (var r = 0; r < jsonResponse["presidents"].president.length; r++) {
tr = document.createElement('tr');
row = jsonResponse["presidents"].president[r];
for (var i = 0; i < properties.length; i++) {
var td = document.createElement('td');
td.appendChild(document.createTextNode(row[properties[i]]));
tr.appendChild(td);
}
table.appendChild(tr);
}
document.getElementById('presidentialTable').appendChild(table);
}
};
xhttp.open("GET", "//Resources/USPresidents.json", true);
xhttp.send();
}
Rewrite the code as follows - https://jsfiddle.net/7gt2be1x/2/
function loadPresidents() {
"use strict";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var data = this.responseText,
jsonResponse = JSON.parse(data),
table = document.createElement('table');
table.setAttribute('class', 'history');
var properties = ['number', 'name', 'date', 'took_office', 'left_office'];
var capitalize = function(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
};
function filterResults(data) {
var input = document.getElementById('input').value;
return data.filter(function(historicalData) {
return historicalData.name.toLowerCase().indexOf(input.toLowerCase()) != -1;
});
}
var tr = document.createElement('tr');
for (var i = 0; i < properties.length; i++) {
var th = document.createElement('th');
th.appendChild(document.createTextNode(capitalize(properties[i])));
tr.appendChild(th);
}
table.appendChild(tr);
var tr, row;
var filtered = filterResults(jsonResponse["presidents"].president);
for (var r = 0; r < filtered.length; r++) {
tr = document.createElement('tr');
row = filtered[r];
for (var i = 0; i < properties.length; i++) {
var td = document.createElement('td');
td.appendChild(document.createTextNode(row[properties[i]]));
tr.appendChild(td);
}
table.appendChild(tr);
}
document.getElementById('presidentialTable').appendChild(table);
}
};
xhttp.open("GET", "//schwartzcomputer.com/ICT4570/Resources/USPresidents.json", true);
xhttp.send();
}

Generate HTML Table with 2 javascript Arrays

Hello I try to generate an HTML Table with two arrays. Where one array is for the Headers and the other one is for the rows. The arrays work like a blast but the generation of the HTML-Table wont work.....
Here is my little Function: (For the arrays and they work like a blast)
function loadDepartments() {
var query = "$select=DepartmentID,WEBName";
getListItems("example.at", "WEBepartments", query, function (results) {
results.forEach(function (result) {
departments.push({
name: result.WEBName,
id: result.DepartmentID
});
});
loadCountries();
},
function (error) {
console.log(error);
});
}
function loadCountries() {
var query = "$select=CountryID,WEBName,Acronym";
getListItems("https://intranet.windkraft.at/", "WEBCountries", query, function (results) {
results.forEach(function (result) {
countries.push({
name: result.WEBName,
id: result.CountryID,
acronym: result.Acronym
});
});
doNextSteps();
},
function (error) {
console.log(error);
});
}
And here my latest Try:
function doNextSteps() {
//Create a HTML Table element.
var table = document.createElement("TABLE");
table.border = "1";
//Get the count of columns and rows.
var columnCount = departments.length;
var rowCount = countries.length;
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = columnCount[0];
row.appendChild(headerCell);
}
//Add the data rows.
for (var i = 1; i < countries.length; i++) {
row = table.insertRow(-1);
for (var j = 0; j < rowCount; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = rowCount[0];
}
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
But wont work the only thing i get is nothing or undefined. And i have no clue why becouse its the first time i try to generate a HTML Table with javascript. So any help would be great.
Thx for your Time and Help.

Categories