I am trying to parse a JSON string from one of the fields on a record within JS and trying to display the array of items on my lightning-datatable. I am using LWC for this implementation.
JSON string:
{"students" :
[
{
"studId" : "089180000AA0091",
"classRank": "43",
"topped": "Biology",
"gradeCode":"CURIOUS",
"subjCode":"989877788"
},
{
"studId" : "089180000AA0092",
"classRank": "44",
"topped": "Biology",
"gradeCode":"SCORER",
"subjCode":"989877788"
}
]
}
LWC's JS:
childRecords = [];
toDisplay = [];
connectedCallback() {
this.data = '';
this.parseData = [];
this.childRecords = [];
this.toDisplay = [];
getJsonString({myId:this.recordId})
.then(result => {
this.data= result;
this.parseData = JSON.parse(this.data);
this.parseData.students.forEach( recItem =>{
console.log(recItem.studId);
console.log(recItem.classRank);
console.log(recItem.topped);
this.childRecords.push(recItem);
});
this.childRecords.forEach(student=>{
this.toDisplay.push(JSON.stringfy(student));
});
})
.catch(error => {
console.log('Errored out.');
});
}
HTML
<lightning-datatable key-field="studId" data={toDisplay} columns={studColumn}
hide-checkbox-column data-id="student">
</lightning-datatable>
So, here is the Columns I have right now.
const COLUMNS = [
{ label: 'StudentID', initialWidth: 180, fieldName: 'studId', type: 'text', sortable : false, wrapText: true },
{ label: 'Class Rank', initialWidth: 300, fieldName: 'classRank', type:'text', sortable : true ,wrapText: true, hideDefaultActions: true},
{ label: 'Topped',initialWidth: 150, fieldName: 'topped', type:'text', hideDefaultActions: true},
{ label: 'Grade Code',initialWidth: 155, fieldName: 'gradeCode', type:'text', wrapText: true, hideDefaultActions: true}
];
I would like to somehow wire the values I get from my parsed JSON to set the value for fieldName
. If there is any better way then this approach, I would like to try it out.
students
object while iterating.fieldName
dynamically? Won't the payload structure always be the same?