Search code examples
javascriptjqueryarraysassociative-array

JavaScript / jQuery: Push items to array / object with same key for each item


I use DataTables and am trying to generate the "aoColumns" values dynamically so that I don't have to hard-code them.

I tried with the below approach but that seems to be wrong.
My guess is that I am overwriting the same key in each row instead of appending it to each other.

Can someone show me how to do this right - considering that the key "mData" stays the same for all values ?

Expected outcome:

    var tableDT = $('#tblReport').dataTable({
        dom: 'Bfrtip',
        "bProcessing": true,
        "sAjaxSource": "data.php",
        "aoColumns": [
            { mData: 'col1' },
            { mData: 'col2' },
            { mData: 'col3' },
            { mData: 'col4' },
            { mData: 'col5' }
        ]

Dynamic approach:

    var reportColsShort = 'col1,col2,col3,col4,col5'; // for testing purposes
    var aoCols = [];
    
    for(var i = 0; i <reportColsShort.length; i++){
        aoCols['mData'] = reportColsShort[i];
    }

    var tableDT = $('#tblReport').dataTable({
        dom: 'Bfrtip',
        "bProcessing": true,
        "sAjaxSource": "data.php",
        "aoColumns": aoCols

Solution

  • You need to create new JSON Object inside your for-loop and then push this value to your main JSON Array.

    Demo Code:

    var reportColsShort = 'col1,col2,col3,col4,col5'; // for testing purposes
    var aoCols = [];
    var colss = reportColsShort.split(",");//split values
    //if array no need of split
    for (var i = 0; i < reportColsShort.split(",").length; i++) {
      var aoColss = {}//decalre this
      aoColss['mData'] = colss[i];//add value to json object
      aoCols.push(aoColss)//push value in main json arry
    }
    console.log(aoCols)