Render an array

Render an array

swdev92swdev92 Posts: 2Questions: 1Answers: 0

I want to display each value in an array with a pre-determined HTML.

My JSON:

{
  "data": [
    {
      "Date": "2019-11-06 09:12:08", 
      "Messages": [
        "Message #: 0", 
        "cookie"
      ], 
      "Type": "ADD"
    }, 
    {
      "Date": "2019-11-06 09:12:08", 
      "Messages": [
        "Message #: 1", 
        "cookie"
      ], 
      "Type": "ADD"
    }
  ]
}

My script

$(document).ready(function () {
        $('#logsTable').DataTable({
            ajax: "/get_json_logs",
            deferRender: true,
            "columns": [
                {"data": "Date"},
                {"data": "Type"},
                {
                    "data": "Messages", "render": function (data) {
                        return '<pre>' + data + '</pre>';
                    }
                }
            ],
        });
    });

I want each message in Messages array to be displayed in a separate pre HTML tag. So it appears like this in my table:

But right now it is displayed like this:

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,166Questions: 26Answers: 4,921

    Thanks for the good example. I put it in a test case for you
    http://live.datatables.net/kaxewigu/1/edit

    I added a couple console.log statements so you can see what is happening. Basically it gets the first element of the array then uses replace to remove the #: and returns the updated string.

    Kevin

  • swdev92swdev92 Posts: 2Questions: 1Answers: 0

    The link you provided is only rendering one of the messages. It should also include 'cookie' too.

    so basically it should be like this:

    Row 1:

    Message 0
    cookie

    Row 2:

    Message 1
    cookie
  • kthorngrenkthorngren Posts: 21,166Questions: 26Answers: 4,921
    Answer ✓

    Its simply a matter of building the HTML string the way you want. The cookie is data[1] so you can add it to the returned string, like this:
    http://live.datatables.net/hobijoza/1/edit

    I suggest testing the columns.render function in the example I have to learn how it works.

    Kevin

This discussion has been closed.