[SalesForce] lightning:datatable set columns dynamicaly

init: function (cmp, event, helper) {


var columns = '[{"label": "Rank", "fieldName": "rank", "type": "text","initialWidth": "70"},{"label": "Advocate", "fieldName": "advocateName", "type": "text", "initialWidth": "150"},{"label": "Company", "fieldName": "company", "type": "text", "initialWidth": "150"},{"label": "References", "fieldName": "references", "type": "text", "initialWidth": "70"},{"label": "Action", "type": "button", "typeAttributes": { "label": "Recommend", "name": "recommend", "title": "Click to Recommend"} }]';

console.log(columns);
var jsonColumns = JSON.parse(columns);
console.log(jsonColumns);
cmp.set('v.mycolumns', jsonColumns);

cmp.set('v.mydata', [{
                rank: '1',
                advocateName: 'Avery Faulkner',
                company: 'Test',
                references: '0'
            },
            {
                rank: '2',
                advocateName: 'Test Adv',
                company: 'Test Adv',
                references: '0'
     }]);
}

Component

<lightning:datatable data="{! v.mydata }"
                     columns="{! v.mycolumns }"
                     keyField="id"
                     onrowselection="{! c.getSelectedName }"
                     onrowaction="{! c.handleRowAction }"
                     hideCheckboxColumn="true"/>

Why I have only one column in datatable?

enter image description here

Best Answer

The initialWidth is an integer property and you have provided the value as text.

Once you provide the columns like this

var columns = '[{"label": "Advocate", "fieldName": "advocateName", "type": "text", "initialWidth": 150},...

it starts working.