Search code examples
javascripttabulator

Tabulator: How to get multiline data on separate rows


I've an object with keys/value pair where values are comma separated in an array.
e.g.

var myObject = { key1 : [v11, v12, v13, v14] , key2 : [v21, v22, v23, v24]};

What I've working now is keys goes in as column headers and all of the array values in single row. The row data appears as comma separated. I've a mutator that converts "," to "\n" which then converts row data and still shows in single row , albeit on different lines.

enter image description here

What I need is to display each value from each array on separate row , just like in excel. And also (if possible) merge rows for keys for corresponding value rows.

enter image description here

Here's relevant code

<script>
    //converts comma to newline
var customMutator = function(value, data, type, params, component){
    return value.join("\n");
}
             var tableData = [
             {id:1, key:"key1", values: ["v11", "v12", "v13", "v14"]},
             {id:1, key:"key2", values: ["v21", "v22", "v23", "v24"]},
             ];
 var table = new
Tabulator("#example-table", {
             data:tableData,
             columns:[
             {title:"key", field:"key", formatter:"textarea"},
             {title:"values",field:"values", formatter:"textarea", mutator:customMutator,},
             ],
         });
 </script>

Solution

  • Because you are only interested in viewing the data and not editing it, the easiest thing is a custom formatter. (If you need to edit the data in that format, then I am not sure how to do that at this time.)

    Your custom formatter will create an element with a border for each item in your value array. This is an example of a custom formatter that you could use.

    function customFormatter(cell, formatterParams, onRendered) {
        const val = cell.getValue();
        const cellDiv = document.createElement('div');
        for (let i = 0; i < val.length; i++){
            const valItemDiv = document.createElement('div');
            valItemDiv.textContent = val[i];
            valItemDiv.style.border = 'purple 1px solid';
            cellDiv.appendChild(valItemDiv);
        }
        return cellDiv;
    }
    

    Here is a full working example. https://jsfiddle.net/nrayburn/sqdvkm5u/11/