Using nested object keys in row

Using nested object keys in row

mpenningmpenning Posts: 1Questions: 1Answers: 0
edited November 2022 in Free community support

Hello all,
I have been looking through examples but have not come across an example using dynamic changing keys of objects in a row and have not been able to successfully get them to work in datatables.

Here is a sample of the data:

{
  "data": {
    "Alice": {
      "City": "Chicago",
      "State": "Illinois"
    },
    "Bob": {
      "City": "Detroit",
      "State": "Michigan"
    }
  }
}

I am trying to get datatables to show in each row consisting of the name, city, and state but having a difficult time. I am not sure how to set the columns.data field. Any help would be much appreciated. Thanks in advance.

$('#myDataTable').DataTable({
      ajax: {
        url: "../api/userdata",
        dataType: "json",
        dataSrc: "data",
        contentType: "application/json"
      },
      columns: [
        { title: "Name", data: "???"},
        { title: "City", data: "???"},
        { title: "State", data: "???"},
      ],
      order: [],
});

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    DataTables doesn't support that format, as it expects constant keys - for you, the name is changing so DataTables wouldn't be able to find it. You can convert that object to an array, as shown in this example. Here, I'm just parsing the data before loading the table. For you, as it's coming via ajax, you would need to do that conversion in ajax.dataSrc (see the last example on that reference page),

    Colin

Sign In or Register to comment.