I'm trying to create a HTML table from JSON data using Javascript. My issue lies within the error TypeError: Cannot read properties of undefined (reading '0')
So I'm wondering how this can be fixed in order to work correctly.
JS code:
const requestUrl6 = 'https://api.npoint.io/1cae29b5fc8900f6cc5a';
const requestJSON6 = async url => {
const response6 = await (await fetch(url)).json();
const keys = Object.keys(response6);
for (let keyIndex = 0; keyIndex < keys.length; keyIndex ){
const limit6 = Math.max(...Object.keys(response6[keys[keyIndex]][0].expenses)) 1;
for(let index6 = 0; index6 < limit6; index6 )
{
let newRow6 = rowTemplate6.cloneNode(true);
newRow6.id = '';
newRow6.querySelector('.Expenses6').innerHTML = response6.expenses[index6];
newRow6.querySelector('.Date6').innerHTML = response6.dt_posted[index6];
newRow6.querySelector('.Purpose6').innerHTML = response6.description[index6];
rowTemplate6.parentNode.appendChild(newRow6);
}
rowTemplate6.parentNode.removeChild(rowTemplate6); }
}
requestJSON6(requestUrl6);
The issue is in this line of code: const limit6 = Math.max(...Object.keys(response6[keys[keyIndex]][0].expenses)) 1;
HTML code:
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
</head>
<body>
<table id="content-table_page6" style="color: rgb(16, 16, 16); font-size: 15px;">
<tr >
<th>Date</th>
<th>Expenses</th>
<th>Lobying Activities</th>
</tr>
<tr id='rowTemplate6'>
<td class='Expenses6' style="text-align:center; font-size: 10px;"></td>
<td class='Date6' style="text-align:center; font-size: 10px;"></td>
<td class='Purpose6' style="text-align:center; font-size: 10px;"></td>
</tr>
</table>
<script src="AAPL_Corporate_lobbying.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
</body>
</html>
CodePudding user response:
however, in the issue code line you gave were no errors for me. Instead, it threw me errors in this
newRow6.querySelector('.Expenses6').innerHTML = response6.expenses[index6];
line. It looks like you forgot to add the sub-keys. You tried to access JSON that would look like this:
{
"expenses": [
"value1",
"value2",
"value3"
]
}
You have to add the other keys to go further in the JSON object. You can do this by replacing
response6.expenses[index6]
with
response6[keys[keyIndex]][0]["expenses"][index6]
I've created a Pen with the working code: https://codepen.io/celharding/pen/KKeYNxY