0

I need guidance in displaying the following data in jquery datatable. The data is as shown below:

let resultList = [{ Name: “User 1”, ID: 1, Course: “ABC”, 
    Scores: [
        {Englisth: 80;Spanish: 75;Math: 100;History:90},
        {Englisth: 81;Spanish: 76;Math: 70;History:80},
        {Englisth: 70;Spanish: 55;Math: 80;History:70}
    ]
}]

The resultList is an array and it has another array in it called Scores.

I want to display the above data in datatable as shown below,

enter image description here

I looked at both, rows().add() and columnDfs options but I don't get how to display this data.

columns: [
        { title: "Name", defaultContent: "" },
        { title: "ID", defaultContent: ""  },
        { title: "Course", defaultContent: "" },
        { title: "English", defaultContent: "" },
        { title: "Spanish", defaultContent: ""  },
        { title: "Math", defaultContent: "" },
        { title: "History", defaultContent: "" }
    ],
    columnDefs: [],
    select: {
        style: 'multi',
        selector: 'td:first-child',
        className: 'selected bg-selected-row'
    },
    order: [1, 'asc']
});

Any suggestion is greatly appreciated.

1 Answer 1

1

The problem you have here is you want to display the scores in table, but are fetching the records for user. You will have to reformat the data for displaying it in the table as shown below:

//Convert data into required format
var resultListFinal = [];
resultList.map(function(val) {
  val.Scores.map(function (score) {
    resultListFinal.push({
      'Name': val.Name,
      'ID': val.ID,
      'Course': val.Course,
      'English': score.English, //Note: I have corrected the spelling of English
      'Spanish': score.Spanish,
      'Math': score.Math,
      'History': score.History
    });
  });
});

Then apply datatable to the reformatted array like this:

$('#resultTable').DataTable({
  data: resultListFinal, //This is the reformatted array
  columns: [{
    title: 'Name',
    data: 'Name'
  }, {
    title: 'ID',
    data: 'ID'
  }, {
    title: 'Course',
    data: 'Course'
  }, {
    title: 'English',
    data: 'English'
  }, {
    title: 'Spanish',
    data: 'Spanish'
  }, {
    title: 'Math',
    data: 'Math'
  }, {
    title: 'History',
    data: 'History'
  }]
});

You can check the entire solution in codepen https://codepen.io/prinkpan/pen/jOWbxdm

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I see reformatting the data is the option for now. Will look for other possible solutions too. +1 from me. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.