How to use JSON object with unique keys instead of JSON array of objects as data source?

How to use JSON object with unique keys instead of JSON array of objects as data source?

shawnjames95shawnjames95 Posts: 6Questions: 2Answers: 0

I have JSON formatted similar to the JSON below.

{
   "Tiger Nixon": {
      "Position": "System Architect",
      "Office": "Edinburgh",
      "Age": 61,
      "Start date": "2011/04/25",
      "Salary": "$3,120"
   },
   "Garrett Winters": {
      "Position": "Director",
      "Office": "Edinburgh",
      "Age": 63,
      "Start date": "2011/07/25",
      "Salary": "$5,300"
   }.
}

I want to make the key containing the name (ex. "Tiger Nixon" and "Garrett Winters" as column 1, then from there on use the values associated with that key as the values for the rest of the columns in that row.

I have played around with the column option but I can't think of how this would be possible.

Is the only way to do this to loop through my object and set it to an array?

This question has an accepted answers - jump to answer

Answers

  • bindridbindrid Posts: 730Questions: 0Answers: 119

    That is not really a properly formatted json object. I would fix it if you can. If you cant, you can do something like this to fix the data before displaying the table:

                var q = [];
                var keys = Object.keys(p);
                $.each(keys, function (i, item) {
                    var details = p[item];
                    q[q.length] = { "name": item, "details": details };
                });
         
                c = { data: q, columns: [{ "data": "name" }, { "data": "details.Office" }, { "data": "details.Position" }, { "data": "details.Age" }, { "data": "details.Salary" }] };
    
                $("#pp").DataTable(c);
    
  • kthorngrenkthorngren Posts: 21,166Questions: 26Answers: 4,921

    Not sure but I think you might be looking for the rowId.

    Kevin

  • allanallan Posts: 63,195Questions: 1Answers: 10,413 Site admin
    Answer ✓

    Actually, the JSON above is fully valid. There us a trailing dot, but I'm guessing that's just a typo in the short example.

    Currently no, DataTables requires an array of items and cannot use an object I'm afraid. You'd need to covert the onject to an array, either client-side or server-side.

    Allan

  • shawnjames95shawnjames95 Posts: 6Questions: 2Answers: 0

    Thank you for the answer. Yes the trailing dot was a typo.

This discussion has been closed.