Read from dynamic JSON object

Read from dynamic JSON object

RevoRevo Posts: 2Questions: 1Answers: 0

I need to read from a JSON object (not via ajax) and dynamically generate/update a table's content and headers. I've been searching and trying for hours now and can't find a solution. Any help would be highly appreciated.

Something like this to generate column headers from an array would be a start:

function generateStatsObject (selectedCropsAndYearsArray) { // eg: ["Barley-2016", "Barley-2017", "Potato-2016"] 

      panelTableData.destroy();
      panelTableData = $('#table_panels').DataTable({
        
        columns: [
            {title:[selectedCropsAndYearsArray]}
        ]
        
          
      });
      panelTableData.draw(); 
    

}

Later I'd like to change selectedCropsAndYearsArray to an object, such as [{title: "Barley-2016", value: "2234"}] and append key:value pairs. title should used column header and value as the actual data.

Cheers!

Answers

  • kthorngrenkthorngren Posts: 20,302Questions: 26Answers: 4,769

    Here is an example I built previously to show how to dynamically get/build the table columns and data from an ajax request. Sounds like your situation is a bit different but I think this might help you get started.

    http://live.datatables.net/fafuyeyu/1/edit

    Kevin

  • RevoRevo Posts: 2Questions: 1Answers: 0

    Thank you!

    But I get the error "Uncaught TypeError: Cannot read property 'style' of undefined"

    var panelTableData;
    function generateStatsObject (selectedCropsAndYearsArray) {
    
        
    
        transformedObject = [];
    
        for (var i=0; i<selectedCropsAndYearsArray.length;i++) {
    
            transformedObject.push({title:selectedCropsAndYearsArray[i],data:selectedCropsAndYearsArray[i]});
                
        }
        
        console.log(transformedObject); 
        
        
        if (typeof panelTableData !== "undefined"){
    
            panelTableData.destroy();
    
        }
        
        panelTableData = $('#table_panels').DataTable({
            //data: transformedObject,
            columns: transformedObject
        });
        panelTableData.draw(); 
        
        
    }
    

    array of objects:

    (2) [{…}, {…}]
    0: {title: "Barley-2016", data: "Barley-2016", sTitle: "Barley-2016", mData: "Barley-2016"}
    1: {title: "Barley-2017", data: "Barley-2017", sTitle: "Barley-2017", mData: "Barley-2017"}
    
  • allanallan Posts: 61,722Questions: 1Answers: 10,108 Site admin

    My guess is that transformedObject contains more entries than there are columns in the table, although without a test case showing the issue it is impossible to say for sure.

    Allan

This discussion has been closed.