Javascript table from array of objects - javascript

I have something like this, but bigger.
[{
"votes":200,
"invalid_votes":140,
"valid_votes":60,
"voting_section":{"level":2, "zone1":"US", "zone2":"Delaware"}
},
{
"votes":300,
"invalid_votes":40,
"valid_votes":260,
"voting_section":{"level":3, "zone1":"US", "zone2":"California", "zone3":"Los Angeles"}
}]
I am trying for hours to transform this array into a table.
My goal is to put in the first column of the table the last zones (in our case zone2 and zone3) in voting_section (for example, the first column will have 2 lines: Delaware and Los Angeles.
In the header of the table I want to put all the other properties(votes, invalid_votes, valid_votes).
The intersection will be completed with the values:
So it has to be something like this:
Here I have my code so far, but I don't think I'm going in a good direction:
function createTableKeyValue2(arrObjects, parentDiv) {
var elTable = document.createElement("table");
elTable.className = "table table-striped table-bordered";
var elTableBody = document.createElement("tbody");
for (var i = 0; i < arrObjects.length; i++) {
var elTableRow = document.createElement("tr");
var elTableDataKey = document.createElement("td");
elTableDataKey.innerHTML = arrObjects[i];
var elTableDataValue = document.createElement("td");
elTableDataValue.innerHTML = arrObjects[i];
//elTableDataValue.id = arrObjects[i].key.split(' ').join('_');
elTableRow.appendChild(elTableDataKey);
elTableRow.appendChild(elTableDataValue);
elTableBody.appendChild(elTableRow);
}
elTable.appendChild(elTableBody);
parentDiv.append(elTable);
}
var votingSection = function(zone) {
var voting_section = [];
var level = zone[0].voting_section.level;
for (var i = 0; i < zone.length; i++) {
voting_section.push(zone[i].voting_section['zone' + level]);
}
return voting_section;
};
createTableKeyValue(votingSection(zone2), resultsTableDiv);
resultTableDiv is a node in the DOM.

I've interpreted your question as though you want to extract 1 zone from voting_section, that zone should have the highest number appended to it.
var data = [{
"votes": 200,
"invalid_votes": 140,
"valid_votes": 60,
"voting_section": {
"level": 1,
"zone1": "US",
"zone2": "Delaware"
}
},
{
"votes": 300,
"invalid_votes": 40,
"valid_votes": 260,
"voting_section": {
"level": 1,
"zone1": "US",
"zone2": "California",
"zone3": "Los Angeles"
}
}
],
html = "";
function getLastZone(voting_section) {
var highestZone = {
zoneNumber: null,
zoneText: null
};
for (var zone in voting_section) {
var checkZone = /zone(\d)/g.exec(zone);
if (checkZone) {
if (parseInt(checkZone[1]) > highestZone.zoneNumber) {
highestZone = {
zoneNumber: [checkZone[1]],
zoneText: voting_section[zone]
};
}
}
}
return highestZone.zoneText;
}
data.forEach(function(e, i) {
html += "<tr>" + "<td>" + getLastZone(e.voting_section) + "</td>" +
"<td>" + e.votes + "</td>" +
"<td>" + e.valid_votes + "</td>" +
"<td>" + e.invalid_votes + "</td>" + "</tr>";
})
document.getElementById("putHere").innerHTML = html;
table {
border-collapse: collapse;
border-left: 1px solid #bbbbbb;
border-top: 1px solid #bbbbbb;
}
th, td {
border-right: 1px solid #bbbbbb;
border-bottom: 1px solid #bbbbbb;
}
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
<table>
<thead>
<th>Zone</th>
<th>Votes</th>
<th>Valid Votes</th>
<th>Invalid Votes</th>
</thead>
<tbody id="putHere"></tbody>
</table>
</body>
</html>

You could create one main function to build the table, from which you could call a row-building function (while iterating over the data rows). I've added an example to my post here.
var data = [{
"votes":200,
"invalid_votes":140,
"valid_votes":60,
"voting_section":{"level":2, "zone1":"US", "zone2":"Delaware"}
},
{
"votes":300,
"invalid_votes":40,
"valid_votes":260,
"voting_section":{"level":3, "zone1":"US", "zone2":"California", "zone3":"Los Angeles"}
}];
var buildTable = function(data, container){
/* Builds one data row into a <tr> element string */
var buildRow = function(rowData){
return `<tr><td>${rowData.voting_section.zone2}</td><td>${rowData.votes}</td><td>${rowData.valid_votes}</td><td>${rowData.invalid_votes}</td></tr>`;
}
/* Reduces the array of row data into one string */
var rows = data.reduce(function(rows, row){
return rows+buildRow(row);
}, '');
/* Creates the full table and includes the rows string */
container.innerHTML = `<table><thead><tr><td></td><td>Votes</td><td>Valid Votes</td><td>Invalid Votes</td></tr></thead><tbody>${rows}</tbody>`;
}
var resultsTableDiv = document.getElementById('results')
buildTable(data, resultsTableDiv);
<div id="results"></div>

You can create a table from it using the javascript DOM objects,
myArray = [{
"votes":200,
"invalid_votes":140,
"valid_votes":60,
"voting_section":{"level":2, "zone1":"US", "zone2":"Delaware"}
},
{
"votes":300,
"invalid_votes":40,
"valid_votes":260,
"voting_section":{"level":3, "zone1":"US", "zone2":"California", "zone3":"Los Angeles"}
}]
table = document.getElementById("myTable")
//In case is is called multiple times this forces the table to be empty
while(table.rows[0] !== undefined) {
table.deleteRow(0)
}
//Creates the empty cell in the top left
row = table.insertRow(0)
row.insertCell(0)
pos = 0
//Creates the column labels
for(var name in myArray[0]) {
if (name !== "voting_section") {
pos += 1
cell = row.insertCell(pos)
cell.innerHTML = name
}
}
//creates the row labels, by changing how the last item is selected or what it contains you can produce a different label
for (var i = 0; i < myArray.length; i++) {
row = table.insertRow(i+1)
lastItem = myArray[i].voting_section[Object.keys(myArray[i].voting_section)[Object.keys(myArray[i].voting_section).length - 1]]
row.insertCell(0).innerHTML = lastItem
}
//creates the values
pos = 0
for(var name in myArray[0]) {
if (name !== "voting_section"){
pos += 1
for (var i = 0; i < myArray.length; i++) {
row = table.rows[i+1]
cell = row.insertCell(pos)
cell.innerHTML = myArray[i][name]
}
}
}

Related

Array object value not counting up in js

I have a problem of some of my object values in my array do not show correct in my html site, it only shows the last number of the array in every .When i make a console log it shows the correct numbers its just in the table it wont do it. it did work before but now i doest not and i do not know what i did that ruined my code. I hope for some quick help that works.
function metric(tryk){
for (var i = 0; i < death_row.length; i++) {
if (tryk === "metric"){
var testMetric = death_row[i].height;
}
if (testMetric === null){
death_row[i].height = 0;
death_row[i].weight = 0;
} else{
var klip1 = death_row[i].height.slice(0,1);
var klip2 = death_row[i].height.slice(3,death_row[i].height.indexOf("'",i+2));
var klip2tal = Number(klip2);
//console.log(klip2);
var regn1 = klip1 * 12;
var regn2 = regn1 + klip2tal;
var regn3 = regn2 * 2.54;
console.log(regn3);
var vaegt = death_row[i].weight/2.2046;
console.log(vaegt);
};
};
var tabel2 = "<table>";
for (var i = 0; i < death_row.length; i++) {
tabel2+="<tr>";
tabel2+="<td>"+death_row[i].first_name +" "+ death_row[i].last_name+"</td>";
tabel2+="<td>"+death_row[i].age_at_execution+" år"+"</td>";
tabel2+="<td>"+regn3+"</td>";
tabel2+="<td>"+vaegt+"</td>";
tabel2+="</tr>";
}
tabel2+="</table>";
document.getElementById("test").innerHTML = tabel2;
};
<div id="test"></div>
<div id="test2"></div>
Assuming that death_row is globally available and you want to have unique values for regn3 and vaegt, you'll need to save those to the individual row objects too.
var regn3 = regn2 * 2.54;
death_row[i].regn3 = regn3;
var vaegt = death_row[i].weight/2.2046;
death_row[i].vaegt = vaegt;
Then you can address them in your table the same way you display the other row values:
tabel2+="<td>"+death_row[i].regn3+"</td>";
tabel2+="<td>"+death_row[i].vaegt+"</td>";
You can construct HTML elements and add them to the document this way.
A for...of loop can set the innerHTML (or any property) of the elements as desired, using data from your array.
const death_row = [
{ first_name: "first1", last_name: "last1", age_at_execution: "age1" },
{ first_name: "first2", last_name: "last2", age_at_execution: "age2" },
{ first_name: "first3", last_name: "last3", age_at_execution: "age3" }
];
const tabel2 = document.createElement("table");
for (let person of death_row) {
let regn3 = "regn3 goes here"
let vaegt = "vaegt goes here"
const row = document.createElement("tr");
const nameCell = document.createElement("td");
nameCell.innerHTML = person.first_name + " " + person.last_name;
row.appendChild(nameCell);
const ageCell = document.createElement("td");
ageCell.innerHTML = person.age_at_execution + " år";
row.appendChild(ageCell);
const regn3Cell = document.createElement("td");
regn3Cell.innerHTML = regn3;
row.appendChild(regn3Cell);
const vaegtCell = document.createElement("td");
vaegtCell.innerHTML = vaegt;
row.appendChild(vaegtCell);
tabel2.appendChild(row);
}
document.getElementById("test").appendChild(tabel2);
td{ border: 1px solid gray; padding: 5px; }
<div id="test"></div>

How to change the element of a cell with the value of the element next to it in Javascript?

In table like the one below in the code snippet I would like that once clicked an item, I want to change the name of the selected cell to the next name corresponding to the sequence like in the array. [square, triangle, circle, oval, pentagon] So if I click "square", now the name appearing on it should be "triangle".
var card = [
{name:'square'},
{name:'triangle'},
{name:'circle'},
{name:'oval'},
{name:'pentagon'}
];
function generateTable(grid, rows, cols) {
var row;
var cells = rows * cols;
for(var i=0; i < cells; i++){
// track row length and insert new ones when necessary
// also creates the first row
if(i % cols == 0) {
row = grid.insertRow(-1);
}
// track our position in the card list
// modulo operator lets us loop through the cards repeatedly
var thisCard = card[i % card.length];
cell = row.insertCell(-1);
cell.innerHTML = thisCard.name;
cell.style.backgroundColor = '#D3D3D3';
}
}
generateTable(document.getElementById('grid'), 7, 7);
<table id="grid">
</table>
"I want the value to change to the next in the sequence" (clarification from a comment that it isn't the element to the right that matters, it's the sequence in the array)
OK, so I would probably use a (delegated) click handler attached to the table element. Get the value of the clicked td element and look it up in the card array, then from there get the next item from the array. Maybe a little something like this:
document.getElementById('grid').addEventListener("click", function(e) {
if (e.target.nodeName.toLowerCase() === "td") {
var currentIndex = card.findIndex(function(shape) {
return shape.name === e.target.innerHTML;
});
e.target.innerHTML = card[(currentIndex + 1) % card.length].name;
}
});
var card = [
{name:'square'},
{name:'triangle'},
{name:'circle'},
{name:'oval'},
{name:'pentagon'}
];
function generateTable(grid, rows, cols) {
var row;
var cells = rows * cols;
for(var i=0; i < cells; i++){
// track row length and insert new ones when necessary
// also creates the first row
if(i % cols == 0) {
row = grid.insertRow(-1);
}
// track our position in the card list
// modulo operator lets us loop through the cards repeatedly
var thisCard = card[i % card.length];
cell = row.insertCell(-1);
cell.innerHTML = thisCard.name;
cell.style.backgroundColor = '#D3D3D3';
}
}
generateTable(document.getElementById('grid'), 7, 7);
<table id="grid">
</table>
I have used the array .findIndex() method to find the item in the array, so if you want to support IE you'll need a polyfill, or of course you could just use a for loop or whatever.
You can access cells by their cellIndex property. So once you have the cell that was clicked on, get the cell to the right (if it exists) and update the innerHTML of the clicked on cell.
function changeName(e){
// Get the element that was clicked on
var cell = e.target;
var row, index;
// If it's a td, update the innerHTML
if (cell && cell.tagName.toLowerCase() == 'td') {
// Get the row that the cell is in
row = cell.parentNode;
// Get index of cell to right
index = cell.cellIndex + 1;
// Make sure cell to right exists
if (row.cells[index]) {
// Update clicked on cell
cell.innerHTML = row.cells[index].innerHTML;
}
}
}
window.onload = function(){
document.querySelector('table').addEventListener('click',changeName);
}
td {
width: 5em;
border: 1px solid #999999;
}
<table>
<tr><td>square<td>triangle<td>circle<td>oval<td>pentagon
</table>
Here is a more concise version:
window.onload = function() {
document.querySelector('table').addEventListener('click',
function(e) {
var cell = e.target;
var next = cell.cellIndex === undefined? null : cell.parentNode.cells[cell.cellIndex + 1];
if (next)
cell.innerHTML = next.innerHTML
});
};
td {
width: 5em;
border: 1px solid #999999;
}
<table>
<tr><td>square<td>triangle<td>circle<td>oval<td>pentagon
</table>
Edit
Updated to loop through the names in succession
var card = [
{name:'square'},
{name:'triangle'},
{name:'circle'},
{name:'oval'},
{name:'pentagon'}
];
function getNextCard(name) {
}
window.onload = function() {
document.querySelector('table').addEventListener('click',
function(e) {
var node = e.target;
var name = node.textContent;
var index;
if (node.tagName.toLowerCase() == 'td') {
index = (card.findIndex(function(obj){
return obj.name == name;
}) + 1) % card.length;
node.textContent = card[index].name;
}
});
};
td {
width: 5em;
border: 1px solid #999999;
}
<table>
<tr><td>square<td>triangle<td>circle<td>oval<td>pentagon
</table>
Please feel free to optimize this solution. Hope this works for you and this is what you want :)
var card = [{
name: 'square'
},
{
name: 'triangle'
},
{
name: 'circle'
},
{
name: 'oval'
},
{
name: 'pentagon'
}
];
function onCellClick(td) {
value = td.innerHTML.trim();
for (var i = 0; i < card.length; i++) {
var index;
if (card[i].name === value) {
index = i + 1;
if (card.length - 1 === i) {
index = 0
}
td.innerHTML = card[index].name;
break;
}
}
}
function generateTable(grid, rows, cols) {
var row;
var cells = rows * cols;
for (var i = 0; i < cells; i++) {
// track row length and insert new ones when necessary
// also creates the first row
if (i % cols == 0) {
row = grid.insertRow(-1);
}
// track our position in the card list
// modulo operator lets us loop through the cards repeatedly
var thisCard = card[i % card.length];
cell = row.insertCell(-1);
cell.innerHTML = thisCard.name;
cell.onclick = function() {
onCellClick(this);
};
cell.style.backgroundColor = '#D3D3D3';
}
}
generateTable(document.getElementById('grid'), 7, 7);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="grid">
</table>

Creating table or multi-dimensional grid using JavaScript

I'm trying to create a word search puzzle and am beginning by generating a table of random letters. I want to have a table of any number by number, so 10X10 for example, but so far I'm only able to generate a column and can't figure out how to create more columns or the entire grid.
var firstCol = [];
for (var i = 0; i <= 10; i++){
var characters = 'ABCDEFGHIJKLMNOPQRSTUVXYZ';
var random = parseInt(Math.random()*characters.length);
var letter = characters.charAt(random); //returning random letter
var innerArrays = ['<td>' + letter + '</td>'];
firstCol.push(innerArrays);
};
for (var i = 0; i <= 10; i++){
document.getElementById('wsBox').innerHTML +=
'<tr>'+ firstCol[i] + '</tr>';
};
and this is my HTML...
<table>
<tbody id="wsBox">
</tbody>
</table>
This is a very basic code.
var cols = 10;
var rows = 10;
var html = "";
for(var i =0; i <= rows; i++) {
html += '<tr>';
for(var h=0; h<= cols; h++) {
var characters = 'ABCDEFGHIJKLMNOPQRSTUVXYZ';
var random = parseInt(Math.random()*characters.length);
var letter = characters.charAt(random); //returning random letter
html += '<td>' + letter + '</td>';
}
html += '</tr>';
}
document.getElementById('wsBox').innerHTML += html;
Here's working code:
http://jsfiddle.net/42dj7jy8/3/
Script
var rows = [];
var colStr = null;
for(var j = 0; j <= 10; j++) {
colStr = "";
var characters = 'ABCDEFGHIJKLMNOPQRSTUVXYZ';
for (var i = 0; i <= 10; i++){
var random = parseInt(Math.random()*characters.length);
var letter = characters.charAt(random); //returning random letter
var cell = '<td>' + letter + '</td>';
colStr += cell;
};
rows.push('<tr>' + colStr + '</tr>');
}
document.getElementById('wsBox').innerHTML += rows.join("");
Some CSS to wash it down with
td {
border: 1px solid black;
padding: 4px;
text-align: center;
vertical-align: middle;
width: 20px;
height: 20px;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
Here's output
This uses arrays to build the cells and rows of the grid which are joined together with the join method. Simply pass the dimensions of the grid into the function. One loop only.
function createGrid(x, y) {
var rows = [], cells = [];
var characters = 'ABCDEFGHIJKLMNOPQRSTUVXYZ';
// a complete grid is x * y dimensions
for (var i = 0, l = x * y; i < l; i++) {
letter = characters.charAt(Math.random() * characters.length);
cells.push('<td>' + letter + '</td>');
// when we reach the last column of the row
// push the cells into the row array and reset
// the cells array
if (i !== 0 && (i + 1) % x === 0) {
rows.push('<tr>' + cells.join('') + '</tr>');
cells = [];
}
}
return rows.join('');
}
Grab the element and use insertAdjacentHTML to add the compiled grid HTML.
var tbody = document.getElementById('wsBox');
tbody.insertAdjacentHTML('beforeend', createGrid(10, 10));
DEMO - 10 x 10 grid
DEMO - 3 x 4 grid

Create HTML table from JavaScript object

I am a beginner of JavaScript and want to display an array of objects in HTML.
The format of the data is like this:
[
{"key":"apple","value":1.90},
{"key":"berry","value":1.7},
{"key":"banana","value":1.5},
{"key":"cherry","value":1.2}
]
I want to use a list with three columns (id, name, relevance) to display them. And the id can increase from 1 automatically.
Could anyone tell me how to write a javascript code to display it?
Please give me some materials or examples to learn.
Explanation
What you want is to fill a table (or another DOMElement) in HTML, with your JavaScript, which is executed dynamically once the page is loaded and your JSON object is received.
You want to loop through the object. The best way to do so would be with a for loop, and making sure our looping variable remains valid for the length of our object (all its attributes).
The best way to get the length of a JSON object is through myJSONObject.length: You select the keys of myJSONObject and return their count.
You can access the values stored in your JSON Object the following way, in your for loop (assuming the looping variable defined is named i): myJSONObject[i].theAttributeIWantToGet
Price formatting breakdown
Now, those prices need to have a proper format, don't they? So we'll check if any of the value attribute has less than 2 characters after the . within them. If they do, we add another decimal 0. We also add a $ before writing the formatted value. Here is a breakdown of how it works:
obj[i].value.toString().substring(startIndex, length)
We want to check the length after the . sign, so our startIndex will be the position of this dot within our string.
obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'),length)
We now need to set the length. We want to find the length of all what's after the dot, so we'll take the length of the whole string just to be safe.
Final result: obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2
This will return true or false. If it's true: There's less than 2 digits after the dot !
We add the if statement and the last zero:
if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2)
obj[i].value += "0";
Also: Why I use innerHTML instead of appendChild().
Solution
JSFiddle
HTML
<table>
<tbody id="tbody"></tbody>
</table>
JSON
[{
"key": "apple",
"value": 1.90
}, {
"key": "berry",
"value": 1.7
}, {
"key": "banana",
"value": 1.5
}, {
"key": "cherry",
"value": 1.2
}]
JavaScript
Note: The JSON object will be named obj in this instance.
var tbody = document.getElementById('tbody');
for (var i = 0; i < obj.length; i++) {
var tr = "<tr>";
/* Verification to add the last decimal 0 */
if (obj[i].value.toString().substring(obj[i].value.toString().indexOf('.'), obj[i].value.toString().length) < 2)
obj[i].value += "0";
/* Must not forget the $ sign */
tr += "<td>" + obj[i].key + "</td>" + "<td>$" + obj[i].value.toString() + "</td></tr>";
/* We add the table row to the table body */
tbody.innerHTML += tr;
}
JSFiddle
It can be simply done by a small & smart process:
<table cellpadding="2" cellspacing="2" border="0" bgcolor="#dfdfdf" width="40%" align="center">
<thead>
<tr>
<th>Name</th>
<th width="20%">Age</th>
<th width="12%">Status</th>
</tr>
</thead>
<tbody id="tableData"></tbody>
</table>
<script type="text/javascript">
var mainObj = [
{
name: "Kapil",
age: 21,
status: "Active"
},
{
name: "John",
age: 28,
status: "Inactive"
},
{
name: "Deos",
age: 18,
status: "Active"
}
];
var k = '<tbody>'
for(i = 0;i < mainObj.length; i++){
k+= '<tr>';
k+= '<td>' + mainObj[i].name + '</td>';
k+= '<td>' + mainObj[i].age + '</td>';
k+= '<td>' + mainObj[i].status + '</td>';
k+= '</tr>';
}
k+='</tbody>';
document.getElementById('tableData').innerHTML = k;
</script>
You can do something like this:
var table = document.createElement("table");
//Add a header
var header = document.createElement("tr");
var idHeaderCell = document.createElement("th");
var nameHeaderCell = document.createElement("th");
var relevanceHeaderCell = document.createElement("th");
header.appendChild(idHeaderCell);
header.appendChild(nameHeaderCell);
header.appendChild(relevanceHeaderCell);
table.appendChild(header);
//Add the rest of the data to the table
for(var i = 0; i < data.length; i++) {
var id = (i + 1);
var name = data[i].key;
var relevance = data[i].value;
var tr = document.createElement("tr");
var idCell = document.createElement("td");
var nameCell = document.createElement("td");
var relevanceCell = document.createElement("td");
idCell.appendChild(document.createTextNode(id));
nameCell.appendChild(document.createTextNode(name));
relevanceCell.appendChild(document.createTextNode(relevance));
tr.appendChild(idCell);
tr.appendChild(nameCell);
tr.appendChild(relevanceCell);
table.appendChild(tr);
}
Here a function for build a table from any collection (array of objects)
Table creator
const data=[
{
name: "Kapil",
age: 21,
status: "Active"
},
{
name: "John",
age: 28,
status: "Inactive"
},
{
name: "Deos",
age: 18,
status: "Active",
testing: 'Gooo!!'
}
]
const createTable=function(data){
const table = document.createElement("table");
const header = document.createElement("tr");
const keys=Object.keys(data[0])
console.log(keys)
for(const key of keys){
const th=document.createElement("th");
th.appendChild(document.createTextNode(key));
header.appendChild(th);
}
table.appendChild(header);
const len=data.length
for(const row of data) {
const tr = document.createElement("tr");
for(const key of keys){
const td = document.createElement("td");
const content=row[key] ||''
td.appendChild(document.createTextNode(content));
tr.appendChild(td);
delete row[key]
}
/****
you can omit next cycle if all object have the same structor or if the first element of collection have all fields
****/
for(const key in row){
const th=document.createElement("th");
th.appendChild(document.createTextNode(key))
keys.push(key)
header.appendChild(th);
const td = document.createElement("td");
const content=row[key] ||''
td.appendChild(document.createTextNode(content));
tr.appendChild(td);
}
table.appendChild(tr);
}
return table
}
Array.map() combined with template literals comes in really handy for rendering HTML markup within Javascript for large objects in a scalable manner:
function tableMarkupFromObjectArray(obj) {
let headers = `
<th>Index</th>
${Object.keys(obj[0]).map((col) =>`
<th>${col}</th>`
).join('')}`
let content = obj.map((row, idx) => `
<tr>
<td>${idx}</td>
${Object.values(row).map((datum) => `
<td>${datum}</td>`
).join('')}
</tr>
`).join('')
let tablemarkup = `
<table>
${headers}
${content}
</table>
`
return tablemarkup
}
let myobj =[
{ "name": "apple", "rel": 1.90 },
{ "name": "berry", "rel": 1.7 },
{ "name": "banana", "rel": 1.5 },
{ "name": "cherry", "rel": 1.2 }
]
document.querySelector("#mydiv").innerHTML = tableMarkupFromObjectArray(myobj)
http://jsfiddle.net/4L7c5vad/
Here is my ES6 solution.
I have used the reduce operation to construct a Set storing the keys from all objects in the array:
function arrayToTable(data) {
const keys = [...data.reduce((all, obj)=>{
Object.keys(obj).forEach(key => all.add(key));
return all;
}, new Set())];
const header = keys.map(key => `<th>${key}</th>`).join('')
const tbody = data.map(row => keys.map(key => `<td>${row[key]}</td>`).join('')).map(row => `<tr>${row}</tr>`)
return `<table>
<thead><tr>${header}</tr></thead>
<tbody>${tbody}</body>
</table>`;
}
Iterate through the list and retrieve the data for each item this way (assuming your data is in a var called data):
for (var i = 0; i < data.length; i++) {
var id = i + 1;
var name = data[i].key;
var relevance = data[i].value;
}
Then, do something with the variables in each loop, print them out however you want.
I am not totally sure what you are asking for. The title of you post seems like you are looking for JSON.stringfy like mentioned in the previous answer but apparently you are not.
Are you trying to create and HTML list, ? Can you please try to explain your need again? I doubt what you are trying to do is complicated and I sure we can help you if you give a little more detail and purpose of what you are trying to do.
I am going to guess that you are trying to display HMTL by looping over you JSON object. Try this pure JavaScript example:
var fruits = JSON.parse('[{"key":"apple","value":1.90}, {"key":"berry","value":1.7}, {"key":"banana","value":1.5}, {"key":"cherry","value":1.2} ]');
var tbl = document.createElement('table');
var thead = document.createElement("thead");
var tbody = document.createElement("tbody")
var tr_head = document.createElement("tr");
var th_id = document.createElement("th");
var th_name = document.createElement("th");
var th_price = document.createElement("th");
th_id.textContent = "Id";
th_name.textContent = "Name";
th_price.textContent = "Price";
tr_head.appendChild(th_id);
tr_head.appendChild(th_name);
tr_head.appendChild(th_price);
thead.appendChild(tr_head);
for(var i = 0, j = fruits.length; i < j; i++) {
var tr_body = document.createElement("tr");
var td_id = document.createElement("td");
var td_name = document.createElement("td");
var td_value = document.createElement("td");
td_id.textContent = i;
td_name.textContent = fruits[i].key;
td_value.textContent = fruits[i].value;
tr_body.appendChild(td_id);
tr_body.appendChild(td_name);
tr_body.appendChild(td_value);
tbody.appendChild(tr_body);
}
tbl.appendChild(thead);
tbl.appendChild(tbody);
console.log(tbl);
Maybe like this:
function obj2htmltable(obj) {
var html = '<table>';
for (var key in obj) {
var value = obj[key].toString();
html += '<tr><td>' + key + '</td><td>' + value + '</tr>';
}
html += '</table>';
return html;
}
If case of nested structure (objects inside object) obj2htmltable() could call itself recursively:
function obj2htmltable(obj) {
var html = '<table>';
for (var key in obj) {
var item = obj[key];
var value = (typeof(item) === 'object') ? obj2htmltable(item) : item.toString();
html += '<tr><td>' + key + '</td><td>' + value + '</tr>';
}
html += '</table>';
return html;
}

Create html table from comma separated strings javascript

I am trying to write a Javascript function which writes the text to (eventually) create the following html tables (I will be passing different length arguments to it to create hundreds of tables):
<table>
<tr><td><u>School</u></td>
<td><u>Percent</u></td>
<tr><td>School 1: </td>
<td>Percent1</td></tr>
<tr><td>School 2: </td>
<td>Percent2</td></tr>
<tr><td>School 3: </td>
<td>Percent3</td></tr>
</table>
The inputs that I have are comma separated strings:
var school_list = "School 1, School 2, School 3"
var pct_list = "Percent1, Percent2, Percent3"
The function needs to be passed school_list and pct_list, and return a string of the html table code above.
Something like this:
var schoolArr = school_list.split(',');
var pctArr = pct_list.split(',');
var table = "<table>";
for (var i=0; i< schoolArr.length; i++) {
table = table + "<tr><td>"+ schoolArr[i]+"</td><td>"+ pctArr[i] +"</td></tr>";
}
table = table + "</table>";
return table;
You can try below code with Jsfiddle demo ::
function createTable(tab) {
var tar = document.getElementById(tab);
var table = document.createElement('TABLE');
table.border = '1';
var tbdy = document.createElement('TBODY');
table.appendChild(tbdy);
for (var j = 0; j < 4; j++) {
var tr = document.createElement('TR');
tbdy.appendChild(tr);
for (var k = 0; k < 2; k++) {
var td = document.createElement('TD');
td.width = '100';
if (k == 0) td.innerHTML = "School" + (j + 1);
else td.innerHTML = "Percent" + (j + 1);
tr.appendChild(td);
}
}
tar.appendChild(table);
}
createTable('tab');
<div id="tab"></div>
var schools = school_list.split(/,\s*/g).join('</td><td>');
var pcts = pct_list.split(/,\s*/g).join('</td><td>');
return '<table><tr><td>' + schools + '</td></tr><tr><td>' + pcts + '</td></tr></table>'
or a better approach is to construct the whole table in DOM and place it in document directly.
function appendTD(tr, content) {
var td = document.createElement('td');
td.appendChild(document.createTextNode(content));
tr.appendChild(td);
}
var table = document.createElement('table');
school_list.split(/,\s*/g).forEach(appendTD.bind(null, table.appendChild(document.createElement('tr'))));
pct_list.split(/,\s*/g).forEach(appendTD.bind(null, table.appendChild(document.createElement('tr'))));
someParent.appendChild(table);
var numberOfSchools = school_list.split(',');
var numberOfPercent = pct_list.split(',');
var htmlOutput= '<table><tr><td><u>School</u></td><td><u>Percent</u></td>';
for(var i = 0 ; i < numberOfSchools.length; i++)
{
htmlOutput += "<tr><td>" + numberOfSchools[i] + "</td>";
htmlOutput += "<td>"+numberOfPercent[i] +"</td></tr>"
}
htmlOutput += "</table>"
And return htmlOutput
Here's a DOM method, highlighs why innerHTML is so popular. DOM methods are pretty fast in execution lately, but the amount of code is a bit tiresome unless there's a good reason to use it.
The amount of code can be significantly reduced with a couple of helper functions so it is on par with innerHTML methods:
var school_list = "School 1, School 2, School 3"
var pct_list = "Percent1, Percent2, Percent3"
function makeTable(schools, percents) {
// Turn input strings into arrays
var s = schools.split(',');
var p = percents.split(',');
// Setup DOM elements
var table = document.createElement('table');
var tbody = table.appendChild(document.createElement('tbody'));
var oRow = document.createElement('tr');
var row;
oRow.appendChild(document.createElement('td'));
oRow.appendChild(document.createElement('td'));
table.appendChild(tbody);
// Write header
row = tbody.appendChild(oRow.cloneNode(true));
row.childNodes[0].appendChild(document.createTextNode('School'));
row.childNodes[1].appendChild(document.createTextNode('Percent'));
// Write rest of table
for (var i=0, iLen=s.length; i<iLen; i++) {
row = tbody.appendChild(oRow.cloneNode(true));
row.childNodes[0].appendChild(document.createTextNode(s[i]));
row.childNodes[1].appendChild(document.createTextNode(p[i]));
}
document.body.appendChild(table);
}
It can be called after the load event, or just placed somewhere suitable in the document:
window.onload = function() {
makeTable(school_list, pct_list);
}

Categories

Resources