Inserting table data under a particular table header from an Object - javascript

Given a Javscript Object:
var obj = {
"results": [{
"B": "Row 1 Col 2"
}, {
"A": "Row 1 Col 1"
"B": "Row 2 Col 2"
}, {
"C": "Row 1 Coll 3"
}
}]
I wish to convert it to a table that looks like the following.
<table border="1">
<thead>
<tr>
<th id="A">A</th>
<th id="B">B</th>
<th id="C">C</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1 Col 1</td>
<td>Row 1 Col 2</td>
<td>Row 1 Col 3</td>
</tr>
<tr>
<td></td>
<td>Row 2 Col 2</td>
<td></td>
</tr>
</tbody>
</table>
Which looks like:
Demo Table Data
More precisely, I'm looking for a way to somehow insert the value of a property directly below it.
javascript:
var cols = obj.results.reduce(function(arr, currObj) {
return arr.concat(Object.keys(currObj).filter(function(key) {
return arr.indexOf(key) == -1
}));
}, []).sort();
// create header from sorted column keys
var header = '<tr><th>' + cols.join('</th><th>') + '</th></tr>';
var rows = obj.results.map(function(item) {
// loop over column keys checking matches to item keys
return '<tr>' +
cols.map(function(key) {
return '<td>' + (item.hasOwnProperty(key) ? item[key] : '') + '</td>';
}).join('') + '</tr>';
}).join('');
var table = '<table border="1">' + header + rows + '</table>';

Might not be the most elegant way but works
var cols = obj.results.reduce(function(arr, currObj) {
return arr.concat(Object.keys(currObj).filter(function(key) {
return arr.indexOf(key) == -1
}));
}, []).sort();
// create header from sorted column keys
var header = '\n<thead>\n\t<tr>\n\t\t<th>' + cols.join('</th>\n\t\t<th>') + '</th>\n\t</tr>\n</thead>';
var j = {}
obj.results.map(function(item) {
// loop over column keys checking matches to item keys
cols.map(function(key) {
if(j[key] == undefined)
{
j[key] = []
}
if (item.hasOwnProperty(key))
{
j[key].push(item[key]);
}
})
});
var rows = []
var index = 0
for(let k in j)
{
rows.push([])
for(let e in j[k])
{
rows[index].push(j[k][e])
}
index += 1
}
function transposeArray(array, arrayLength){
var newArray = [];
for(var i = 0; i < array.length; i++){
newArray.push([]);
};
for(var i = 0; i < array.length; i++){
for(var j = 0; j < arrayLength; j++){
newArray[j].push(array[i][j]);
};
};
return newArray;
}
rows = transposeArray(rows, 3)
var rowsStr = "";
for(let k in rows)
{
rowsStr += '\n\t<tr>';
for(let e in rows[k])
{
if(rows[k][e] != undefined)
{
rowsStr += '\n\t\t<td>' + rows[k][e]+ '\t\t</td>'
}
else
{
rowsStr += "\n\t\t<td></td>"
}
}
rowsStr += '\n\t</tr>';
}
var table = '<table border="1">' + header + "\n<tbody>" + rowsStr + "\n</tbody>" + '\n</table>';

Related

Converting JSON array in HTML table using JQuery

My JSON Array containing date and key-value pairs of alphabets. I need columns as date values and rows heading as Alphabets.
{
"error":0,
"data":[
{
"date":"2017-12-01",
"A":1,
"B":2
},
{
"date":"2017-12-02",
"A":2,
"B":3
}
]
}
I want to create table as given below
Alpha 2017-12-01 2017-12-02
A 1 2
B 2 3
My HTML Code containing datatable for table formatting:
<table id="report" class="table table-striped table-bordered">
<thead>
<tr>
<th>Alpha</th>
</tr>
</thead>
<tbody></tbody>
</table>
And JQuery ajax get response that calls the API:
$.ajax({
url: 'userData/01/2018',
success: function(response) {
let reportData = response.data;
let i = 0;
let j = 1;
let k = 0;
let table = document.getElementById('report');
let tr = table.tHead.children[0];
reportData.forEach(function(data) {
let row = table.insertRow(j);
if (i == 0) {
let th = document.createElement('th');
th.innerHTML = data.date;
tr.appendChild(th);
}
if (k == 0) {
let keys = Object.keys(data);
for (let p = 1; p < keys.length; p++) {
let cell = row.insertCell(k);
cell.innerHTML = keys[p];
for (let q = 1; q < keys.length; q++) {}
}
}
});
}
});
I am able to insert headers as table columns but facing an issue in data insertion.
slight changes in your json string,
HTML:
<table id="report"></table>
JavaScript:
var jsonString = '{"error": 0,"Alpha": [{"date": "2017-12-01","A": 1,"B": 2},{"date": "2017-12-02","A": 2,"B": 3}]}';
var s = '';
$.each(JSON.parse(jsonString), function(i, j) {
if (i == 'Alpha') {
s += '<thead><th>' + i + '</th>';
$.each(j, function(k, val) {
s += '<th>' + val.date + '</th>';
});
s += '</thead>';
$('#report').html(s);
for (var l = 0; j.length; l++) {
if (l == 0) {
s = '<tbody><tr><td> ' + Object.keys(j[l])[l + 1] + ' </td>';
s += '<td> ' + j[l].A + ' </td><td>' + j[l].B + '</td></tr>';
$('#report').append(s);
} else {
s = '<tr><td>' + Object.keys(j[l])[l + 1] + '</td><td>' + j[l].A + '</td><td>' + j[l].B + '</td></tr>';
$('#report').append(s);
}
s += '</tbody>';
}
}
});
For reference - https://jsfiddle.net/zvxqf9mz/

jQuery recursive find

<table id="TemplateBindVarsTable" class="table">
<tr>
<td class="control-label">${MeetingName}</td>
<td class="form-control" style="border:0"><input id="${MeetingName}"
type="text"></td>
</tr>
<tr>
<td class="control-label">${MeetingLocation}</td>
<td class="form-control" style="border:0"><input id="${MeetingLocation}"
type="text"></td>
</tr>
</table>
I have the following jQuery code that goes against this:
function processTemplate() {
var rows = $('#TemplateBindVarsTable').find("tr");
for (var i = 0; i < rows.length; i++) {
// NONE OF THESE WORK
var cells = rows[i].children();
var key = rows[i].find("td.control-label").text();
var val = rows[i].find("td.control-label>input").val();
alert('key: ' + key + ", val: " + val);
}
}
What am I missing? Shouldn't I be able to get rows back and then run a find/children on them?!
You just need to modify it a little like following to convert DOM object to jQuery object on which you can execute jQuery's methods like .children() and .find():
function processTemplate() {
var rows = $('#TemplateBindVarsTable').find("tr");
for (var i = 0; i < rows.length; i++) {
// NONE OF THESE WORK
var cells = $(rows[i]).children();
var key = $(rows[i]).find("td.control-label").text();
var val = $(rows[i]).find("td.control-label>input").val();
alert('key: ' + key + ", val: " + val);
}
}

Looping through HTML table with Javascript/jQuery

I am struggling to figure out how to loop through a table in HTML.
I have a 2D Javascript object that I would like to populate cells with index i,j from myObject[i][j]. I have a basic html table template but with blank <td></td> tags. I have looked at ways to do it in jQuery and Javascript, but to no avail.
Edit: Here's my code:
var table = document.getElementById("myTable");
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
col = myObject[i][j]
}
}
My HTML is just a standard table eg.:
<table id="myTable">
<thead>
<tr>
<th></th>
</tr>
<tr>
<td></td>
</tr>
</thead>
<tbody>
<tr>
<th></th>
<td></td>
</tbody>
</table>
Any help would be greatly appreciated.
Thanks #bulicmatko
You can try something like this: jsfiddle.net/pt9go1s6
You can try something like this:
HTML:
<div id="tableWrap"></div>
JS:
var tableWrap = document.getElementById("tableWrap");
var data = [
['First Name', 'Last Name', 'Age'],
['Johnny', 'Bravo', '27'],
['Bugs', 'Bunny', '35'],
['Mickey', 'Mouse', '35'],
];
var table = "<table>";
for (var i = 0; i < data.length; i++) {
table += "<tr>";
for (var j = 0; j < data[i].length; j++) {
table += "<td>" + data[i][j] + "<td>";
}
table += "</tr>";
}
table += "</table>";
tableWrap.innerHTML = table;
Here is the demo.
Hope it helps ;)
A jQuery solution could be use child related selectors to filter relevant cells.
var ar = [
['A', 'B'],
['C', 'D']
];
for (var r = 0; r < 2; ++r) {
for (var c = 0; c < 2; ++c) {
$('table tr:nth-of-type(' + (r + 1) + ') td:nth-of-type(' + (c + 1) + ')').text(ar[r][c]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>.</td>
<td>.</td>
</tr>
<tr>
<td>.</td>
<td>.</td>
</tr>
</table>

Inserting table <td> cell under a particular header <th> from an Object

Given a Javscript Object:
var obj = {
"results": [{
"B": "Row 1 Col 2"
}, {
"A": "Row 2 Col 1"
"B": "Row 2 Col 2"
}, {
"C": "Row 3 Coll 3"
}
}]
I wish to convert it to a table that looks like the following.
<table border="1">
<thead>
<tr>
<th id="A">A</th>
<th id="B">B</th>
<th id="C">C</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Row 1 Col 2</td>
<td></td>
</tr>
<tr>
<td>Row 2 Col 1</td>
<td>Row 2 Col 2</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td>Row 3 Col 3</td>
</tr>
</tbody>
</table>
Which looks like:
More precisely, I'm looking for a way to somehow insert the value of a property directly below it. And creating a new header as when a new property emerges while successively reading the object. This is a better way of approaching the problem I feel, as it is more versatile for an arbitrary object.
This is why I was wondering if there was any HTML tag or jQuery way such that I can directly insert a cell under a particular header of my choice instead of calculating and inserting appropriate number of "<td></td>" till I get to the right cell.
Fiddle: https://jsfiddle.net/kqsozme5/2/
Following doesn't care how many columns there are, and works on totally arbitrary object config.
It sorts the column names prior to looping through data again to build rows and creates empty cells as necessary
// create array of column keys and sort
var cols = obj.results.reduce(function(arr, currObj) {
return arr.concat(Object.keys(currObj).filter(function(key) {
return arr.indexOf(key) == -1
}));
}, []).sort();
// create header from sorted column keys
var header = '<tr><th>' + cols.join('</th><th>') + '</th></tr>';
var rows = obj.results.map(function(item) {
// loop over column keys checking matches to item keys
return '<tr>' +
cols.map(function(key) {
return '<td>' + (item.hasOwnProperty(key) ? item[key] : '') + '</td>';
}).join('') + '</tr>';
}).join('');
var table = '<table border="1">' + header + rows + '</table>';
var obj = {
"results": [{
"B": "Row 1 Col 2"
}, {
"A": "Row 2 Col 1",
"B": "Row 2 Col 2"
}, {
"C": "Row 3 Coll 3"
}]
};
// create array of column keys and sort
var cols = obj.results.reduce(function(arr, currObj) {
return arr.concat(Object.keys(currObj).filter(function(key) {
return arr.indexOf(key) == -1
}));
}, []).sort();
// create header from sorted column keys
var header = '<tr><th>' + cols.join('</th><th>') + '</th></tr>';
var rows = obj.results.map(function(item) {
// loop over column keys checking matches to item keys
return '<tr>' +
cols.map(function(key) {
return '<td>' + (item.hasOwnProperty(key) ? item[key] : '') + '</td>';
}).join('') + '</tr>';
}).join('');
var table = '<table border="1">' + header + rows + '</table>';
$('body').append(table);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Html:
<tbody id = "idTBody">
Jquery:
for(var result in obj.results)
{
for(var col in obj.results[result])
{
$("#idTBody").append("<tr>");
if(col == 'A'){ $("#idTBody").append("<td>"+obj.results[result][col]+"</td>");}
else {$("#idTBody").append("<td></td>");}
if(col == 'B'){ $("#idTBody").append("<td>"+obj.results[result][col]+"</td>");}
else {$("#idTBody").append("<td></td>");}
if(col == 'C'){ $("#idTBody").append("<td>"+obj.results[result][col]+"</td>");}
else {$("#idTBody").append("<td></td>");}
$("#idTBody").append("</tr>");
}
}
why don't use arrays
var object = {
result: [['a', 'b', 'c'],
['', 'rows1 col2', ''],
['row2 col1', 'row2 col2', '']]
}
it's easy to convert to tables.
Assuming Your Object is :
var obj = {
"results": [{
"A": "",
"B": "Row 1 Col 2",
"C": ""
}, {
"A": "Row 2 Col 1",
"B": "Row 2 Col 2",
"C": ""
}, {
"A": "",
"B": "",
"C": "Row 3 Coll 3"
}
}]
HTML Would Be:
<table id="trialTable" border="1">
<thead>
<tr>
<th id="A">A</th>
<th id="B">B</th>
<th id="C">C</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JQuery will Be:
var tbody = $("#trialTable > tbody");
tbody.empty();
$.each(obj.results, function(index, data) {
var tr = $("<tr>");
var td = $("<td>");
tr.append($('<td>', {
text: data.A
}));
tr.append($('<td>', {
text: data.B
}));
tr.append($('<td>', {
text: data.C
}));
tbody.append(tr);
});
you will get your expected output.As far as i know, using jQuery instead of simple javascript is always easy and less confusing.

Unable to retieve the particular value of cell on table using javascript

I am using the following code to retrieve the values of a particular cell of a table.:
function addCatAttr()
{
var tbl = document.getElementById("tblAttributes1");
if (tbl.rows.length > 1)
{
for ( var i = 1 ; i < tbl.rows.length ; i++ )
{
var r = tbl.rows[i];
var catname1 =r.cells[0].document.getElementsByTagName("input").item(1).value;
var lifecycycleattr1 = r.cells[0].document.getElementsByTagName("input").item(2).value;
var stateattr1 = r.cells[0].document.getElementsByTagName("input").item(3).value;
}
}
}
and my html code is :
<table id="tblAttributes1">
<tr>
<td>Category</td>
<td>Life Cycle Attribute</td>
<td>State Attribute</td>
</tr>
<tr>
<td>cat1</td>
<td>pf</td>
<td>state</td>
</tr>
</table>
I want to retrieve each value of a particular.
Its just an example.I have more thane two rows for which i need for loop to get the values of each cell.
See if this points you in the right direction:
function addCatAttr()
{
var tbl = document.getElementById("tblAttributes1");
if (tbl.rows.length > 1)
{
for ( var i = 1 ; i < tbl.rows.length ; i++ )
{
var r = tbl.rows[i];
var catname1 =r.cells[0].innerText;
var lifecycycleattr1 = r.cells[1].innerText;
var stateattr1 = r.cells[2].innerText;
alert('catname1: ' + catname1 + '\r\n' +
'lifecycycleattr1: ' + lifecycycleattr1 + '\r\n' +
'stateattr1: ' + stateattr1 + '\r\n');
}
}
}
<table id="tblAttributes1">
<tr>
<td>Category</td>
<td>Life Cycle Attribute</td>
<td>State Attribute</td>
</tr>
<tr>
<td>cat1</td>
<td>pf</td>
<td>state</td>
</tr>
</table>
<input type="button" onclick="addCatAttr()" value="Click me" />
This can help better...
function addCatAttr()
{
var tbl = document.getElementById("tblAttributes1");
if (tbl.rows.length > 1)
{
for ( var i = 1 ; i < tbl.rows.length ; i++ )
{
var r = tbl.rows[i];
var catname1 =r.cells[0].innerHTML;
var lifecycycleattr1 = r.cells[1].innerHTML;
var stateattr1 = r.cells[2].innerHTML;
alert('catname1: ' + catname1 + '\r\n' +
'lifecycycleattr1: ' + lifecycycleattr1 + '\r\n' +
'stateattr1: ' + stateattr1 + '\r\n');
}
}
}
<table id="tblAttributes1">
<tr>
<td>Category</td>
<td>Life Cycle Attribute</td>
<td>State Attribute</td>
</tr>
<tr>
<td>cat1</td>
<td>pf</td>
<td>state</td>
</tr>
</table>
<input type="button" onclick="addCatAttr()" value="Click me" />
You need to apply two for loops one for table length and the other for the each td in tr. This is the code.
var table = document.getElementById('tblAttributes1'),
rows = table.getElementsByTagName('tr');
for (var i = 0; i< rows.length; i++) {
var tds = rows[i].getElementsByTagName('td');
for(var x=0;x<tds.length;x++){
console.log(tds[x].innerHTML);
}
And the fiddle is-
http://jsfiddle.net/09q6n3m2/16/

Categories

Resources