Search code examples
javascriptarraysdatatableyuiyui-datatable

JS: How to dynamically load data into a datatable?


I need a datatable with column sorting using the YUI library. So I am trying to adapt this example:

YUI().use("datatable-sort", function(Y) {
    var cols = [
        {key:"Company", label:"Click to Sort Column A", sortable:true},
        {key:"Phone", label:"Not Sortable Column B"},
        {key:"Contact", label:"Click to Sort Column C", sortable:true}
    ],
    data = [
        {Company:"Company Bee", Phone:"415-555-1234", Contact:"Sally Spencer"},
        {Company:"Acme Company", Phone:"650-555-4444", Contact:"John Jones"},
        {Company:"Industrial Industries", Phone:"408-555-5678", Contact:"Robin Smith"}
    ],
    table = new Y.DataTable({
        columns: cols,
        data   : data,
        summary: "Contacts list",
        caption: "Table with simple column sorting"
    }).render("#sort");
});

I need to dynamically add the data into this table. So I passed a two-dimensional array from the server-side to the JS function. It is an array consisting of arrays which represent rows, then the data inside the inner arrays represents the table's cells data. The array on the server-side was:

Array ( [0] => Array ( [0] => Name [1] => Age [2] => CGPA ) [1] => Array ( [0] => Alex [1] => 23 [2] => 2.5 ) [2] => Array ( [0] => Bob [1] => 24 [2] => 3 ) [3] => Array ( [0] => Mike [1] => 22 [2] => 3.9 ) ) 

This is something I was trying to do (see the for loop to put data in the cols =[...]) but it does not work, not even the alert($rowsArray); part. Aparently this function does not seem to work at all.

M.mod_quiz.init_tabView = function(Y, params) {

    var $rowArray= params.key1;

    alert($rowArray);

    YUI().use("datatable-sort", function(Y) {
                    var cols = [
                        for (i=0; i<$rowArray.length; i++) {
                            {key:"Column "+i , label: $rowArray[0][i] , sortable=true}
                        }
                        /*{key:"Company", label:"Sort Column A", sortable:true},
                        {key:"Phone", label:"Sort Column B", sortable:true},
                        {key:"Contact", label:"Sort Column C", sortable:true}*/
                    ],
                    data = [
                        {Company:"Company Bee", Phone:"415-555-1234", Contact:"Sally Spencer"},
                        {Company:"Acme Company", Phone:"650-555-4444", Contact:"John Jones"},
                        {Company:"Industrial Industries", Phone:"408-555-5678", Contact:"Robin Smith"}
                    ],
                    table = new Y.DataTable({
                        columns: cols,
                        data   : data,
                        summary: "Contacts list",
                        caption: "Table with simple column sorting"
                    }).render(params.key2);
                    });
};

QUESTION:

So how can I dynamically load the data into this datatable from the array?


Solution

  • Your code has a Uncaught SyntaxError: Unexpected token for here:

    var cols = [
        for (i=0; i<dummyArray.length; i++) {
            {key:"Column "+i , label: dummyArray[0][i] , sortable=true}
        }
        //...
    ],
    

    Code inside the array block [] is expecting variables or objects of some kind (e.g. ["foo"] or [someVariable]). But you are putting a for loop within the array which is causing the error.

    Assuming we were passed a dummy array of the format you prescribed (since I cannot access the actual array from your code), you could do this:

    YUI().use("datatable-sort", function(Y) {
    
        // dummyArray since I cannot access your external array.
        var dummyArray = [
            ["Name", "Age", "CGPA"],
            ["Alex", 23, 2.5],
            ["Bob", 24, 3],
            ["Mike", 22, 3.9]   
        ];
    
        // Get the array of labels from the 2d array.
        var labels = dummyArray[0];
        var cols = [];
        for (var i = 0; i < labels.length; i++) {
            cols.push({key: "Column " + i, label: labels[i], sortable: true});
        }
    
        // Get the 2d array and then remove the labels with a shift().
        var values = dummyArray;
        values.shift();
        var data = [];
        for (var i = 0; i < values.length; i++) {
    
            // Create a row object and map each value to its corresponding key.
            var row = {};
            for (var j = 0; j < values[i].length; j++) {
                row["Column " + j] = values[i][j];
            }
    
            // Add the row.
            data.push(row);
        }
    
        // Create the dataTable.
        var table = new Y.DataTable({
            columns: cols,
            data   : data,
        }).render("#sort");
    });