I’m getting data from an API and I want to display this data in a table with 3 columns and dynamic rows- that’s because of the API data
I have this code here:
})
})
//console.log(await response.json())
const balancestoken = await response.json()
function generateTableHead(table, data) {
let thead = table.createTHead();
let row = thead.insertRow();
for (let key of data) {
let th = document.createElement("th");
let text = document.createTextNode(key);
th.appendChild(text);
row.appendChild(th);
}
}
function generateTable(table, data) {
for (let element of data) {
let row = table.insertRow();
for (key in element) {
let cell = row.insertCell();
let text = document.createTextNode(element[key]);
cell.appendChild(text);
}
}
}
let table = document.querySelector("table");
let data = Object.keys(balancestoken[0]);
generateTableHead(table, data);
generateTable(table, balancestoken);
}
When using this code I get following output(table):
token_address name symbol logo thumbnail decimals balance 0x925841cf448a6c350bd19a7a0bdff93da9760a53 SafeCoom SAFECOOM null null 9 108221437157689 0xf68c9df95a18b2a5a5fa1124d79eeeffbad0b6fa Anyswap-BEP20 ANY null null 18 1000000000000000000 0xd22202d23fe7de9e3dbe11a2a88f42f4cb9507cf Minereum BSC MNEB null null 8 15000000000000 0x373233a38ae21cf0c4f9de11570e7d5aa6824a1e ALPACAFIN.COM ALPACA null null 18 28102000000000000000000000
This are the columns I get: token_address name symbol logo thumbnail decimals balance
Which is the default response by the API
How can I select only token_address, symbol and balance and display them in my table?
Advertisement
Answer
Add conditional expression for key. Here is the code:
function generateTableHead(table, data) {
let thead = table.createTHead();
let row = thead.insertRow();
for (let key of data) {
// add this expression
if (key == "token_address" || key == "symbol" || key == "balance")
{
let th = document.createElement("th");
let text = document.createTextNode(key);
th.appendChild(text);
row.appendChild(th);
}
}
}
function generateTable(table, data) {
for (let element of data) {
let row = table.insertRow();
for (key in element) {
// add this expression
if (key == "token_address" || key == "symbol" || key == "balance") {
let cell = row.insertCell();
let text = document.createTextNode(element[key]);
cell.appendChild(text);
}
}
}
}