Skip to content Skip to sidebar Skip to footer

Create Javascript Array (json Format) For Datatables Aocolumndefs

I'd like to create the following JSON data for DataTables parameter aoColumnDefs: var aryJSONColTable = [ {'sTitle': 'Column00', 'aTargets': [0]},

Solution 1:

I suggest you change from a for..in loop to a standard for loop because iterating over an array with for..in is "dangerous" in that if you're using a library that adds properties/methods to the Array.prototype then the loop will iterate over those too.

Also, with a for..in the iterator i will be a string, creating "aTargets" : ["0"], and you want it to be a number to create "aTargets" : [0].

var aryColTableChecked = ["column00", "column01", "column02", "column03"];
var aryJSONColTable = [];

for (var i = 0; i <  aryColTableChecked.length; i++) {
    aryJSONColTable.push({
                      "sTitle": aryColTableChecked[i],
                      "aTargets": [i]
                    });
};

Seems to work fine: http://jsfiddle.net/nnnnnn/Ek8tr/

NOTE: What you're producing is not JSON, it is an array of objects. (JSON is a data-interchange format that is always a string. JSON looks like JS object literal and array literal syntax, but it's not the same thing.)

Solution 2:

for...in is for objects not arrays and aryColTableChecked is an array. You can do it like this:

var arr = [];
var max = 3; // zero basedfor (var i = 0, n; i <= max; i++) {
    n = i > 9 ? '' + i : '0' + i; // make sure it has 2 digits
    arr.push({
        sTitle: 'Column' + n,
        aTargets: [i] // why array here?            
    });
}

Post a Comment for "Create Javascript Array (json Format) For Datatables Aocolumndefs"