简体   繁体   English

在 jquery 数据表中显示数据

[英]Displaying data in jquery Datatable

I need guidance in displaying the following data in jquery datatable.我需要指导在 jquery 数据表中显示以下数据。 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. resultList 是一个数组,其中包含另一个名为 Scores 的数组。

I want to display the above data in datatable as shown below,我想在数据表中显示上述数据,如下所示,

在此处输入图像描述

I looked at both, rows().add() and columnDfs options but I don't get how to display this data.我查看了rows().add()columnDfs选项,但我不知道如何显示这些数据。

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.非常感谢任何建议。

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您可以在 codepen https://codepen.io/prinkpan/pen/jOWbxdm中查看整个解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM