2

I'm very new to this whole area of js and datatables.

How can this be represented in datatables

var data = {"jaxm":
    {
      "name": "Tiger Nixon",
      "position": "System Architect"
    },
    "jaxb" :
    {
     "name": "Garrett Winters",
     "position": "Accountant"
    }

}

I tried

$(duTable).DataTable({
    data:  data,
});

not sure if this possible without arrays or not but even I couldnt print single row in datatables using

$(duTable).DataTable({
    data:  data.jaxm,
});
1
  • What do you expect the table to look like for that sample input?
    – trincot
    Apr 30, 2017 at 21:17

1 Answer 1

3

You cannot (the short answer). The above is more like a hash table, or a kind of associate array: You have an object with multiple keys (not indexes) each of them holding an object. You need to sanitize such construct into an indexed array :

function sanitizeData() {
  var d = [];
  Object.keys(data).forEach(function(key) {
    d.push(data[key]);
  });
  return d;
}

var table = $('#example').DataTable({
  data:  sanitizeData(),
  // **and** instruct dataTables which object property belongs to which column
  columns: [
    { data: 'name' },
    { data: 'position' }
  ]
})  

See demo -> http://jsfiddle.net/0c52ra0c/

It is basically just an algorithmic version of

var table = $('#example').DataTable({
  data:  [data.jaxm, data.jaxb],
  columns: [
    { data: 'name' },
    { data: 'position' }
  ]
})  

which would do the same. So you could use data: [data.jaxm] as a solution for the last attempt of "print single row". Either way, you need to pass an indexed array to dataTables.

1
  • Thanks for your answer, this does the job, but thinking of it... it's very weird that datatables don't allow using this kind of json data :S Nov 21, 2018 at 8:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.