3

When using datatables, I get 'no data available in table' when using an object instead of array:

var data1 =
{
    "status": "success",
    "districts": {
        "1": {
            "district_number": "1",
            "district_name": "district one"
        },
        "2": {
            "district_number": "2",
            "district_name": "district two"
        }
    },
    "time": "1.109s"
};

var table1 = jQuery("#data_table1").DataTable({
    "data": data1.districts,
    "aoColumns": [
        { "mData": "district_number" },
        { "mData": "district_name" }    
    ]
});

I can get an array to display in a datatable using mData as follows:

var data2 =
{
    "status": "success",
    "districts": [
        {
            "district_number": "1",
            "district_name": "district one"
        },
        {
            "district_number": "2",
            "district_name": "district two"
        }
    ],
    "time": "1.109s"
};

var table2 = jQuery("#data_table2").DataTable({
    "data": data2.districts,
    "aoColumns": [
        { "mData": "district_number" },
        { "mData": "district_name" }    
    ]
});

https://jsfiddle.net/w93gubLv/

Is there a way to get datatables to utilize the object in the original format, or must I convert the object to an array?

1 Answer 1

1

You can write your own function to convert one format to another, for example:

function formatData(data){
   var result = [];
   for(prop in data){
      if(data.hasOwnProperty(prop)){
         result.push( data[prop] );
      }
   }
   return result;
}

You can then later use it to pass data to jQuery DataTables as shown below.

var table1 = jQuery("#data_table1").DataTable({
    "data": formatData(data1.districts),
    "aoColumns": [
        { "mData": "district_number" },
        { "mData": "district_name" }    
    ]
});

See updated jsFiddle for code and demonstration.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but I already knew that an array works... I'm asking if an datatables can accept the native object.
@FishBulbX, it accepts array of arrays or array of objects. The solution in your case is to convert object into array of objects.

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.