Reputation: 31
I'm trying my best to loop through JSON data that I get from API and display it in the html table. I parsed the original JSON and displayed data accesing it's elements like this:
JSON(the data is from api):
{"PrekesID":656851,"Kodas":"6DUSA000000122","SandKodas1":"20402","Likutis_PP":0,"Likutis":11,"KAPKodas":"5902115799686","KAPPavad":"PRAUSTUVO VOŽTUVAS S","Kaina":40},{"PrekesID":656851,"Kodas":"6DUSA000000122","SandKodas1":"20406","Likutis_PP":11,"Likutis":11,"KAPKodas":"5902115799686","KAPPavad":"PRAUSTUVO VOŽTUVAS S","Kaina":40}
The whole json is decalred as "content" so:
let jsn=JSON.parse(content);
document.getElementById("Prekes_Kodas").innerText="Kodas: "+jsn.Kodas;
document.getElementById("Prekes_Barkodas").innerText="Barkodas: "+jsn.KAPKodas;
And till this point everything wokrs fine. But I'm facing a problem that if JSON type is object and I loop through it and access it's elements or even get the length. Any suggestions?
Function(data is the parsed JSON):
function warehouseQuant(data){
let table = document.getElementById("myTable");
for (let i = 0; i < data.length; i++ ){
let row = `<tr>
<td>${data[i].Kodas}</td>
<td>${data[i].Kaina}</td>
<td>${data[i].Likutis}</td>
</tr>`
table.innerHTML += row
}
}
Upvotes: 0
Views: 2666
Reputation: 16865
Assemble all the rows and insert it as one monolithic chunk of html.
Your data doesn't have the outer brackets, but I'm assuming it's an array of objects. (If it's originally provided as you present it, it's not valid JSON.)
const data = [{"PrekesID":656851,"Kodas":"6DUSA000000122","SandKodas1":"20402","Likutis_PP":0,"Likutis":11,"KAPKodas":"5902115799686","KAPPavad":"PRAUSTUVO VOŽTUVAS S","Kaina":40},{"PrekesID":656851,"Kodas":"6DUSA000000122","SandKodas1":"20406","Likutis_PP":11,"Likutis":11,"KAPKodas":"5902115799686","KAPPavad":"PRAUSTUVO VOŽTUVAS S","Kaina":40}];
const warehouseQuant = data =>
document.getElementById("myTable").innerHTML = data.map(
item => ([
'<tr>',
['Kodas','Kaina','Likutis'].map(
key => `<td>${item[key]}</td>`
),
'</tr>'
])
).flat(Infinity).join('');
warehouseQuant(data);
<table id="myTable"></table>
Upvotes: 4