I have trouble when fetching data from JSON. I currently have:
- Function that outputs div elements and HTML table structure
- Function that outputs
<th>elements with values from JSON database - Function that outputs
<tr>elements for upcoming<td>elements, it returns equal number of rows as number of rows in JSON data structure
Now here comes the problem, I started building a function that generates data for <td> elements from JSON file. I tested my 'path/selection' with console.log() which I marked with comment at the end of the line // RETURNS ERROR. I think it is caused because some of data structure have less data than I want to loop them. In such cases I want it to output string such as '-'. What I ask of you is the cleanest, simplest way to loop such data from tables.
It is also nessesery to understand JSON table data structure. There are two JSON files, the one has data for <th> elements and IDs that are linked with another JSON files that contain data for <td> elements. Here is Javascript code, and under it I will also include JSON code.
Javascript (jQuery) code:
$.getJSON('data/lige.json',
function (lige) {
$.getJSON('data/ponude.json',
function (ponude) {
// store all output in array
var output = [];
// generate structure elements
function gen_structure() {
for (var i = 0; i < lige.lige.length; i++) {
var heading_data = lige.lige[i].naziv;
output.push('<div class="head">'+heading_data+'</div>');
output.push('<div class="body">');
output.push('<table>');
output.push('<thead><tr colspan="3">'+gen_thead(i)+'</tr></thead>');
output.push('<tbody>'+gen_tbody(i)+'</tbody>');
output.push('</table>');
output.push('</div>');
}
}
// generate thead data
function gen_thead(i){
thead_data = [];
for (var i2 = 0; i2 < lige.lige[i].razrade[0].tipovi.length; i2++) {
thead_data.push('<th>'+lige.lige[i].razrade[0].tipovi[i2].naziv+'</th>');
}
return thead_data.join('');
}
// generate tbody data
function gen_tbody(i){
tbody_data = [];
for (var i3 = 0; i3 < lige.lige[i].razrade[0].ponude.length; i3++) {
tbody_data_id = lige.lige[i].razrade[0].ponude[i3];
tbody_data.push('<tr class="'+tbody_data_id+'">'+gen_td_data(i3)+'</tr>');
}
return tbody_data.join('');
}
// generate <td> data
function gen_td_data(i3){
var get_ponude = ponude[i3];
console.log(get_ponude.tecajevi[i3].tecaj); // RETURNS ERROR
return '<td>'+i3+'</td>';
}
// print output on page
function print_output(){
$('#data-output').append(output.join(''))
}
// function calls
gen_structure();
print_output();
});
});
The error it returns console.log returns:
TypeError: get_ponude.tecajevi[i3] is undefined
tecajeviandi3at the time of the error? It seems thattecajevidoes not have a value at the indexi3