How to print array data inside a table - javascript

So I have this code where I'm trying to print(physical print as in paper) a table when a button is clicked, which is populated with array data.
I managed to print the array data but I can not seem to find on how to put this in a table.
also is there a better way than document.write()I am not a huge fan of it ?
var Obj = [];
function printDiv(){
var divContents = document.getElementsByClassName("test")
console.log(divContents)
//if($("div").hasClass("test") == true){// can use jquery hasfind in order to check if acive class exists if yes get content of child divs
//expand if this option is better
//console.log('istrue');
//}
for(var i = 0; i< divContents.length; i++){
Obj.push(divContents[i].textContent +'</br>')
}
var a = window.open('','','height=500,width=500');
a.document.write('<html>');
a.document.write('<body><h1>Div contents are<h1><br>');
a.document.write('<table><tbody><tr>')
a.document.write('<td>'+ Obj.join(' ')+'<td>');
a.document.write('</tr></tbody></table></body></html>');
a.document.close();
a.print();
Obj = [];
}
expected outcome would be:
work order and date are not yet populated this is just a test file to use in a bigger project.
jsfiddle : https://jsfiddle.net/yLz7stxr/
thanks in advance.

here is the solution you just need to replace ${} in code link.
code: https://jsfiddle.net/vnxd1pew/3/

I assume we got an array of objects here.
const dataObject = {'name': null, 'age': null, 'favoriteFood': null};
let data = [];
let row = {...dataObject};
row.name = 'John';
row.age = '10';
row.favoriteFood = 'Pancakes';
data.push(row);
row = {...dataObject};
row.name = 'Jenny';
row.age = '11';
row.favoriteFood = 'Pie';
data.push(row);
row = {...dataObject};
row.name = 'James';
row.age = '12';
row.favoriteFood = 'Fries';
data.push(row);
// build table header
let tableHeaderColumns = Object.keys(data[0]).map(colKey => `<th>${colKey}</th>`).join('');
const tableHeader = `<tr align=left>${tableHeaderColumns}</tr>`;
// build table rows
let i = 0;
let tableRows = '';
let greyStyle = 'background-color: #EEE;';
data.forEach(function(rowObject) {
const row = Object.values(rowObject).map(colValue => `<td>${colValue}</td>`).join('');
let rowStyle = '';
if(++i%2) {
rowStyle = greyStyle;
}
tableRows += `<tr style='${rowStyle}'>${row}</tr>`;
});
// build table (add desired styling)
const table = `<table cellspacing=0 width=500 border=1 borderColor=#EEE style='border-collapse: collapse;'>${tableHeader}${tableRows}</table>`;
// for demonstration display in div
document.querySelector('div').innerHTML = table;
<div />

Related

sum up user input with javascript

I'm trying to store a user input in a variable and output it.
I actually thought it would be very easy, but right now I'm stuck on this task
I'm trying to store this in an array. but I would also be happy if it was simply stored in a variable and I could output it.
I've been searching for it for a long time, but I have the feeling that I don't know exactly what to look for
here is my code:
let inputValuePrice = document.getElementById("myInput2").value;
let outputSumme = document.getElementById("summe");
outputSumme = parseFloat(inputValuePrice);
let sum = [];
sum.push(outputSumme);
console.log(sum);
<input type="number" id="myInput2" />
<input type="text" id="summe" />
edit:
I'm sorry. I'll explain it again in more detail. I want to add the number after each entry. It is a kind of to-do list with products and prices. each product is entered one by one along with the price. I would then like to add up the price of each product. In this case it is enough for me if it is first output in the console. If it is correct then I will let it output to the html.
if you need to calculate the sum of all inputs values as an integer or a float number it's very simple. you can use a simple function to sums all of your array elements like this:
let inputValuePrice = document.getElementById("myInput2").value;
let outputSumme = document.getElementById("summe");
outputSumme = parseFloat(inputValuePrice);
let sum = [];
sum.push(outputSumme);
console.log(getSumOfArray(sum));
function getSumOfArray(array){
let sumOfElements=0;
for (let i=0;i<array.length;i++){
sumOfElements=sumOfElements+array[i];
}
return sumOfElements;
}
If your array elements are all numbers you can use the reduce operator as follows:
const sumOfArray = sum.reduce((a, b) => a + b, 0)
Unfortunately I don't understand how it works. I have now the products with prices in the indexedDB in my code. There I wanted to read them out and sum them up again in an array. I'll send you the whole code. I would be very grateful for an explanation. what is wrong with my thinking? Here is my code.
This snippet is in a function that when run puts the products in a list in the HTML. The products are created in a foreach loop and in that I intercept the prices and send them outside of the function to another function which then has the data to calculate with. I hope it is understandable. I'll link the whole code at the end of this thread.
let products = makeTransaction('produkte', "readonly");
let request = products.getAll();
request.addEventListener('success', (event) => {
event.preventDefault();
document.querySelector('#product-list').innerHTML = "";
let data = event.target.result;
data.forEach((element) => {
/*-----------Elemente Kreieren------------*/
let li = document.createElement("li");
let edit = document.createElement('i');
let spanPrimary = document.createElement('span');
let inputLabel = document.createElement('label');
let productName = document.createElement('span');
let productPrice = document.createElement('span');
let spanSecondary = document.createElement('span');
let checkBox = document.createElement('input');
let closeBtn = document.createElement("span");
/*-----------Elemente einfügen------------*/
li.setAttribute('data-key', element.id);
productName.appendChild(document.createTextNode(element.title));
productPrice.appendChild(document.createTextNode(element.price + " €"));
spanPrimary.appendChild(productName);
spanPrimary.appendChild(productPrice);
inputLabel.appendChild(checkBox);
spanSecondary.appendChild(inputLabel);
li.appendChild(edit);
li.appendChild(spanPrimary);
li.appendChild(spanSecondary);
li.appendChild(closeBtn);
/*-----------Elemente klassifizieren------------*/
li.className = "mdl-list__item mdl-shadow--2dp";
edit.className = "material-symbols-outlined icon-edit-document";
edit.textContent = 'edit_document';
spanPrimary.className = "mdl-list__item-primary-content";
spanSecondary.className = "mdl-list__item-secondary-action";
inputLabel.className = "mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect";
productName.className = 'product-text';
productPrice.className = 'product-preis';
checkBox.className = "mdl-checkbox__input";
checkBox.setAttribute('id', 'my-id');
checkBox.setAttribute('type', 'checkbox');
closeBtn.className = "material-symbols-outlined hiding-list-item";
closeBtn.textContent = 'close';
componentHandler.upgradeElement(li);
let list = document.getElementById("product-list").appendChild(li);
// Füge die "edit" Funtion hinzu
let editieren = document.getElementsByClassName("icon-edit-document");
for (let i = 0; i < editieren.length; i++) {
editieren[i].onclick = function() {
showProducts(element.id);
}
}
// Füge die "close" Button Funktion hinzu
let close = document.getElementsByClassName("hiding-list-item");
for (let i = 0; i < close.length; i++) {
close[i].onclick = function() {
deleteProduct();
}
}
// Function for totalizing product prices
let produktPreis = element.price
sumPrice(produktPreis);
});
});
request.addEventListener('error', (event) => {
console.log(event.target.error);
});
}
and now the summation...
function sumPrice(produktPreis) {
produktPreis = parseFloat(produktPreis);
let arr = [];
arr.push(produktPreis);
console.log(getSum(arr));
console.log(sumOfArray);
function getSum(array) {
let sumOfElements = 0;
for (let i = 0; i < arr.length; i++) {
sumOfElements = sumOfElements + array[i];
}
return sumOfElements;
}
}
I've always been able to help myself. But I can't get any further with this supposedly simple thing.
and for the completeness. Here is my temporarily hosted website and Github. Thanks also for the previous replies.
Project site
https://liquefied-stripe.000webhostapp.com/
Github
https://github.com/StevoEs/Einkaufsliste/blob/main/main.js
Thanks!

Accessing property's array with a specific id

What i wanted to do is access random property for example let1, let2 with their first string in array which is ID "1" , "2" , "3" , "4" , "5".
brojleta is actually that ID i mentioned before, it is different from id down there(var id = item[0][1]). What i need is to get all other strings based on their ID. I tried it like this :
var data = {
let1:[["1","2","10.2.2019.","11.2.2019.","Beograd Aerodrom","Amsterdam Aerodrom","30","12000"]],
let2:[["2","4","15.2.2019.","16.2.2019","Amsterdam Aerodrom","Rim Aerodrom","30","8000"]],
let3:[["3","6","25.2.2019.","28.2.2019.","Rim Aerodrom","Beograd Aerodrom","30","8000"]],
let4:[["4","8","13.2.2019.","14.2.2019.","Beograd Aerodrom","Moskva Aerodrom","30","13000"]],
let5:[["5","10","1.3.2019.","4.3.2019.","Beograd Aerodrom","New York Aerodrom","30","18000"]]
};
function getParamValue(brojleta) {
var location = decodeURI(window.location.toString());
var index = location.indexOf("?") + 1;
var subs = location.substring(index, location.length);
var splitted = subs.split("&");
for (i = 0; i < splitted.length; i++) {
var s = splitted[i].split("=");
var pName = s[0];
var pValue = s[1];
if (pName == brojleta) {
return pValue;
}
}
}
var brojleta = getParamValue("id");
var item = data.find(item => item[0][0] === brojleta);
var id = item[0][1]
var datumpolaska = item[0][2]
var datumdolaska = item[0][3]
var polazniaerodrom = item[0][4]
var dolazniaerodrom = item[0][5]
var brojsedista = item[0][6]
var cenakarte = item[0][7]
var data1 = data.let1[0];
var data2 = data.let2[0];
var data3 = data.let3[0];
var data4 = data.let4[0];
var data5 = data.let5[0];
/* this is the code for adding data from array to table */
$(document).ready(function(){
var row1cells = $("#row1 td");
var row2cells = $("#row2 td");
var row3cells = $("#row3 td");
var row4cells = $("#row4 td");
var row5cells = $("#row5 td");
for (var index=0; index<8; index++) {
$(row1cells[index]).html(data1[index]);
$(row2cells[index]).html(data2[index]);
$(row3cells[index]).html(data3[index]);
$(row4cells[index]).html(data4[index]);
$(row5cells[index]).html(data5[index]);
}
});
To make your code work you should choose variable data to be an array of arrays instead of an object. Then you can run var item = data.find(item => item[0] === brojleta); and similar operations.
It would look like this:
var data = [["1","2","10.2.2019.","11.2.2019.","Beograd Aerodrom","Amsterdam Aerodrom","30","12000"],
["2","4","15.2.2019.","16.2.2019","Amsterdam Aerodrom","Rim Aerodrom","30","8000"],
["3","6","25.2.2019.","28.2.2019.","Rim Aerodrom","Beograd Aerodrom","30","8000"],
["4","8","13.2.2019.","14.2.2019.","Beograd Aerodrom","Moskva Aerodrom","30","13000"],
["5","10","1.3.2019.","4.3.2019.","Beograd Aerodrom","New York Aerodrom","30","18000"]];
I think you really want this:
Remove the || 3 // test #3 after testing
Try removing the 3 from the input and click search too
var data = {
let1:[["1","2","10.2.2019.","11.2.2019.","Beograd Aerodrom","Amsterdam Aerodrom","30","12000"]],
let2:[["2","4","15.2.2019.","16.2.2019","Amsterdam Aerodrom","Rim Aerodrom","30","8000"]],
let3:[["3","6","25.2.2019.","28.2.2019.","Rim Aerodrom","Beograd Aerodrom","30","8000"]],
let4:[["4","8","13.2.2019.","14.2.2019.","Beograd Aerodrom","Moskva Aerodrom","30","13000"]],
let5:[["5","10","1.3.2019.","4.3.2019.","Beograd Aerodrom","New York Aerodrom","30","18000"]]
};
function getParamValue(brojleta) {
return new URLSearchParams(document.location.search.substring(1)).get(brojleta)
}
function show(item) {
$tr = $("<tr/>"), $tbd = $("#tbd");
$.each(item,function(_,fld) {
$tr.append("<td>"+fld+"</td>");
})
$tr.appendTo($tbd);
}
function showAll() {
Object.keys(data).forEach(function(key) {
show(data[key][0]);
})
}
$(function() {
$("#search").on("click",function() {
$("#tbd").empty();
var brojleta = $("#broj_leta").val();
if (brojleta) show(data["let"+brojleta][0])
else showAll();
});
var brojleta = getParamValue("id") || 3 // test #3
if (brojleta) $("#broj_leta").val(brojleta);
$("#search").trigger("click");
})
th, td { border:1px solid lightgrey; padding: 3px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="broj_leta" /><button id="search">Search</button>
<table>
<thead>
<tr>
<th>id</th>
<th>Datumpolaska</th>
<th>Datumdolaska</th>
<th>Plazniaerodrom</th>
<th>Dolazniaerodrom</th>
<th>Brojsedista</th>
<th>Cenakarte</th>
</tr>
</thead>
<tbody id="tbd">
</tbody>
</table>
You can first filter the data based on ID and then map your required variable to final output array in below code output.
var brojleta = 1;
const mappedarray = Object.entries(data).filter((k,v)=>{return k[0] == "let"+brojleta});
console.log(mappedarray[0][1][0]);
You can use the lodash function find().
This is the same function as Array.find but it works on Object.
https://lodash.com/docs/4.17.11#find

Put certain JSON data arrays into a table after using getJson command

How do I use the below code to pull certain details like country name and capital only into a table with drop down headers? Or can you suggest any plain English Youtube videos where I can learn how to do this or example courses where I can teach myself.
<script>
$(document).ready(function () {
//for example details in url below
var url = 'https://restcountries.eu/rest/v1/all';
$.getJSON(url, function (data) {
console.log(data)
// var arrItems = []; // THE ARRAY TO STORE JSON ITEMS.
// $.each(data, function (index, value) {
// arrItems.push(value); // PUSH THE VALUES INSIDE THE ARRAY.
// });
console.log(arrItems)
// EXTRACT VALUE FOR TABLE HEADER.
var col = [];
var arrItems = data.countries;
console.log(arrItems)
var firstCountry = arrItems[0]
console.log(firstCountry)
for (var i = 0; i < arrItems.length; i++) {
for (var key in arrItems[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < arrItems.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = arrItems[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
});
});
There's a lot of looping inside of looping, which can increase the time and space complexity - meaning, the more data, the slower this solution will become as well as in general this looks like it will be difficult to maintain.
I would first put as much of the html that you can in the static html and just append the dynamic html to the <tbody>.
You can use the Array.reduce static method to generate a string from your data. One thing you can do to make this easier to understand is stick with either mostly appending DOM nodes or using innerHTML. If you stick with innerHTML, you can create template strings for the cells and the rows.
This will make the code more declarative in nature and functional as well as composeable.
$(document).ready(function() {
//for example details in url below
var url = 'https://restcountries.eu/rest/v1/all';
$.getJSON(url, function(data) {
const html = buildHTML(data);
const tbody = document.querySelector('#showData tbody');
tbody.innerHTML = html;
});
});
const tableCellTemplate = (val) => {
return `<td>${val}</td>`;
};
const tableRowTemplate = (val) => {
return `<tr>${val}</tr>`;
};
function buildHTML(data) {
return data.reduce((prev, next) => {
const nameCell = tableCellTemplate(next.name);
const codeCell = tableCellTemplate(next.alpha2Code);
return prev + tableRowTemplate(nameCell + codeCell);
}, '');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="showData">
<table>
<thead>
<tr>
<th>Name</th>
<th>alpha2Code</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>

How to use JavaScript, Ajax or jQuery to display array data in table

Right now I am getting the data like this which works fine but I want to auto display it in a table. I have a button which is clicked and should display the result into a table or should create the table and display any way would be fine.
$result = array();
while ($row = mysql_fetch_assoc($res)) {
$result[$i][0] = $row['fname'];
$result[$i][1] = $row['lname'];
$result[$i][2] = $row['membershipid'];
}
return $result;
any help will be great
Given a data structure of
[
{
fname:"john",
lname:"doe",
membershipid: "1234"
}
]
This function should work for n rows of data
function createTable(dataArray){
var table = document.createElement('table');
var tablerows = dataArray.map(function(datarow){
var tablerow = document.createElement('tr');
for (var value in datarow){
var cell = document.createElement('td');
cell.innerText = datarow[value];
tablerow.appendChild(cell);
}
return tablerow;
});
for (var i = 0; i < tablerows.length; i++){
table.appendChild(tablerows[i]);
}
return table;
}
Then
var table = createTable(dataArray);
document.getElementById('Whatever dom node').appendChild(table);

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;
}

Categories

Resources