i am getting the data by fetching api. here is after fetching data from API, i am getting data something like this:
const info={
"suggesstion":0,
"idea":{
"prod": [
{
"group": {
"subj": "English",
"class": "one",
"section": "1A"
},
},
{
"group": {
"subj": "Physics",
"class": "nine",
"section": "2A"
},
},
{
"group": {
"subj": "Math",
"class": "Ten",
"section": "3A"
},
}
]
}
}
Now when i try to call the data in html table, i am using a function so that i can call the values in table together. here is my function.
const tableD= info?.idea?.prod.map((info) => {
const nS= [],
nC= [],
nSec= [];
nS.push(info.group.subj)
nC.push(info.group.class)
nSec.push(info.group.section)
let table= []
for (let a in nS) {
for (let b in nC) {
for (let c in nSec) {
const nSAll= nS[a],
nCAll= nC[b],
nSecAll= nSec[c];
table =
`<td>${nSAll}</td>
<td>${nCAll}</td>
<td>${nSecAll}</td>
</tr>`
}
}
}
return table;
}).join(' ');
console.log(tableD);
now when i try to use it in html i get this table:
but i want to add serial number for each row in a column like this here will be 1 ,2 ,3
here is my html:
<table >
<thead>
<tr>
<th>No</th>
<th>Subj</th>
<th>Class</th>
<th>Section</th>
</tr>
</thead>
<tbody>
<tr>
<td>${htmlDatasheet}</td>
</tr>
</tbody>
</table>
How can i do that in the function, anyone can help me? Thanks for your trying in advance!
CodePudding user response:
You can maintain one variable and use incremented value in each iteration
....
let counter = 1; //declare here
const tableD= info.idea.prod.map((info) => {
....
table =
`<td>${counter }</td> //use here
<td>${nSAll}</td>
<td>${nCAll}</td>
<td>${nSecAll}</td>
</tr>`
....
CodePudding user response:
Use index variable on the map function to get the index value.
const tableD = info?.idea?.prod.map((info, index) => {
const nS = [],
nC = [],
nSec = [];
nS.push(info.group.subj)
nC.push(info.group.class)
nSec.push(info.group.section)
let table = []
for (let a in nS) {
for (let b in nC) {
for (let c in nSec) {
const nSAll = nS[a],
nCAll = nC[b],
nSecAll = nSec[c];
table =
`<tr>
<td>${index 1}</td>
<td>${nSAll}</td>
<td>${nCAll}</td>
<td>${nSecAll}</td>
</tr>`
}
}
}
return table;
}).join(' ');