0

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

10
  • TypeError: get_ponude.tecajevi[i3] is undefined Commented Nov 24, 2015 at 5:22
  • What is the value of tecajevi and i3 at the time of the error? It seems that tecajevi does not have a value at the index i3 Commented Nov 24, 2015 at 5:24
  • the value of i3 is 2 at that moment. When it is 0 and 1 (since its loop) it returns alot of data that is marked with "tecaj: within JSON. Commented Nov 24, 2015 at 5:29
  • Im not sure what you mean by that. Honestly, you'd be better off showing us your data and the table structure you are trying to end up with. You'd be better served by using one function to build everything possibly using nested loops, but we'll need to see a sample of the data and the resultant table Commented Nov 24, 2015 at 5:33
  • It is good to understand that i3 is number of rows. But the problem is with the number of columns. Commented Nov 24, 2015 at 5:42

1 Answer 1

1

You might need to do a bit of tweaking but this should get you very close:

   $.getJSON('data/lige.json', function (lige) {
  lige=lige.lige; // the file actually has an object whose first key is lige and we name the variable lige, to avoid confusion, normalize it here
  $.getJSON('data/ponude.json',function (ponude) {
    var tables=[];
    $.each(lige, function(li, le) {
      var lige_naziv = le.naziv; // string
      var lige_tipovi =le.razrade[0].tipovi; // array of objects, represents header values
      var lige_ponude=le.razrade[0].ponude; // array of int, represents row ids

      var title='<div class="head">'+lige_naziv+'</div>';

      var headers= li == 2 ? ['<th colspan="3"></th>'] : ['<th colspan="4"></th>']; // make long part of header
      var neededColumns=[]; // this part is key
      $.each(lige_tipovi, function(lti, lte) {  // lte =  [ {"naziv": "1" },...... ]
        headers.push('<th>'+lte.naziv+'</th>');
        neededColumns.push(lte.naziv); // track which ones we need for later
      });
      headers='<tr>'+headers.join('')+'<tr>';

      var trs=[];
      $.each(lige_ponude, function(lpi, lpe) {  // lige_ponude =  [ 8991909, .... ]  ,  lpe =  8991909

        var found_ponude=false; // find the one with this id in the other json set, start out as false
        $.each(ponude, function(pi, pe) {  // pe = {  "broj":"12", "id":8991909, ....... }
          if(pe.id==lpe){
            found_ponude=pe; // found it
            return false;
          }
        });
        if(found_ponude){ // make sure we found one
          var tds=['<td>'+found_ponude.broj+'</td><td>'+found_ponude.naziv+'</td>'];
          // now we loop over neededColumns NOT all of this group's values because there might be more on the group than on our table
          $.each(neededColumns, function(nci, nce) {  // neededColumns = [ 1, x, 2, ....]  , represents header columns that need to be filled in
            var found_ponude_tecajevi=false; // find the stored column value for this column, start out as false
            $.each(found_ponude.tecajevi, function(fpti, fpte) {  // tecajevi = [ { "tecaj":4.0,"naziv":"1"},... ]  , represents column values stored on object
              if(fpte.naziv==nce){ // found it
                found_ponude_tecajevi=fpte.tecaj || '-';
                return false;
              }
              else found_ponude_tecajevi ='-'; //didnt find it
            });
            tds.push('<td>'+found_ponude_tecajevi+'</td>')
          });
          tds.splice(1, 0, '<td>Time Here</td>');
          if(li==2){// we are on the second table and need to insert the signal icon as the 3rd column
            tds.splice(1, 0, '<td>Icon Here</td>');
          }
          trs.push('<tr data-ponude-id="'+lpe+'">'+tds.join('')+'</tr>'); // create row
        }
      });
      tables.push(title+'<table><thead>'+headers+'</thead><tbody>'+trs.join('')+'</tbody> </table>'); // create table
    });
    $('#data-output').html(tables.join('')); // add to page
  });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.