Render a DataTable column using data from multiple fields

Render a DataTable column using data from multiple fields

schnittoschnitto Posts: 5Questions: 3Answers: 0

Hi everyone,

when creating my DataTable I'm using the render function to manipulate the content shown.

Example:

{
   "data": "actors",
   "render": function(data, type, row) {
       return $.map(data, function(d, i) {
            return d.firstname + ' ' + d.lastname;
        }).join(', ');
   }
},

For more complex columns (where I want to combine the data of multiple fields) I would use the row variable. In that there is all the data I need (independent from the "actors"-data)

Now I found another solution:

{
      "data": function(row, type, set) {
            //code...
       }
},

What's the better way to go? Does one solution have any advantages over the other?

Thanks

Answers

  • DailSoftwareDailSoftware Posts: 11Questions: 1Answers: 0
    edited September 2019

    I usually use first approach when I need data from any property except when I need multiple properties that belong to root, and the second when two or more properties belong to root.

    Example:

    For this object:

    {
    "propertyA" : "Foo",
    "propertyB": "Bar",
    "complexProperty": {
        "propertyC": "Foo",
        "propertyD": "Bar",
    }
    }
    

    I would use:

    {
       "name": "cd"
       "data": "complexProperty",
       "render": function(data, type, row) {
           return data.propertyC + data.propertyD;
       }
    },{
          "name": "ab"
          "data": function(row, type, set) {
                return row.propertyA + row.propertyB
           }
    },
    

    I do this in order to make the code more maintainable (if the json representation changes and it is a really nested object, it is much easier to change the "data" if it is just a string in most cases).

    I think you can also use row property on render and totally avoid data.

    I'm not sure about performance, though.

This discussion has been closed.