I have the following table and want to convert it into JSON in a specific way
<table>
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>A1</td>
<td>A2</td>
<td>A3</td>
</tr>
<tr>
<td>B1</td>
<td>B2</td>
<td>B3</td>
</tr>
<tr>
<td>C1</td>
<td>C2</td>
<td>C3</td>
</tr>
</tbody>
</table>
My expected output would be like this as I need to compare the data over UI in html table and a json file having expected data (Note: there may be a varying number of rows):
{
"myrows" : [
{
"Column 1" : "A1",
"Column 2" : "A2",
"Column 3" : "A3"
},
{
"Column 1" : "B1",
"Column 2" : "B2",
"Column 3" : "B3"
},
{
"Column 1" : "C1",
"Column 2" : "C2",
"Column 3" : "C3"
}
]
}
How can this be accomplished?
CodePudding user response:
const rows = document.querySelectorAll("tbody tr");
const result = {
myrows: []
};
rows.forEach(r => {
const rData = {}
r.querySelectorAll("td").forEach((c, i) => {
rData[`column_${i 1}`] = c.innerHTML;
})
result.myrows.push(rData)
})
console.log(result);
<table>
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>A1</td>
<td>A2</td>
<td>A3</td>
</tr>
<tr>
<td>B1</td>
<td>B2</td>
<td>B3</td>
</tr>
<tr>
<td>C1</td>
<td>C2</td>
<td>C3</td>
</tr>
</tbody>
</table>
CodePudding user response:
It's fairly straight forward to loop over rows then cells in the row.
Use index values from each()
command to give you access to the expected value in the JSON.
const expected = { "myrows" : [
... // as in the question, abreviated here
]}
it('check the table', () => {
cy.get('table tbody tr').each(($row, rowIndex) => {
cy.wrap($row).find('td').each(($cell, cellIndex) => {
const text = $cell.text()
expect(text).to.eq(expected.myrows[rowIndex][`Column ${cellIndex}`]
})
})
})