jQuery DataTable add dynamic columns

余生长醉 提交于 2021-02-11 17:57:21

问题


I have a JSON object like below (dataSource) in that JSON object the property 'viewClasses' sometimes comes as blank, here what I want to do is if 'viewClasses' have any record I want to add a dynamic column to the table and the name of the column header will be the value of 'viewClasses.class', I have tried the below code but it's not working as expected.

Here is the result of the below code -

Here how I want this to be-

var dataSource = [{
  "Name": "PI61890",
  "portfolioName": "PGIM Emerging Markets Debt Local Currency Fund",
  "StartDate": "2020-10-31T00:00:00",
  "EndDate": "2020-10-31T00:00:00",
  "processDate": "2020-10-31T00:00:00",
  "viewDetails": {
    "Name": "Management",
    "Code": "MGMT",
    "category": "Asset",
    "description": "Asset Description",
    "viewClasses": [{
        "class": "A",
        "amount": 2000.0
      },
      {
        "class": "B",
        "amount": 3000.0
      }
    ]
  },
}];

var column = [];

function AddColumn() {
  $.each(dataSource[0].viewDetails.viewClasses[0], function(key, value) {
    var my_item = {};
    my_item.data = key;
    my_item.title = key;
    column.push(my_item);
  });
}

$('#example').dataTable({
  data: dataSource[0].viewDetails.viewClasses,
  "columns": column,
  "paging": false,
  "bInfo": false
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
<style src="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css"></style>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<div class="container">
  <div class="row">
    <div class="col-md-12">
      <table id="example" class="table table-striped" width="100%"></table>
    </div>
  </div>
</div>

回答1:


Your source data needs to be iterated in two different ways, to build the two different dynamic arrays which DataTables needs: - column data and row data.

Firstly you have two columns, A and B. To build the array for these, you can use the following:

var dynamicColumns = [];

columnData.forEach(function (columnItem) {
  // extract the column definitions:
  var dynamicColumn = {};
  dynamicColumn['data'] = columnItem['class'];
  dynamicColumn['title'] = 'Heading ' + columnItem['class'];
  dynamicColumns.push(dynamicColumn);
});

I chose not to use the jQuery iterator because I want access to each object in the array.

This gives me the following structure:

[
  {
    "data": "A",
    "title": "Heading A"
  },
  {
    "data": "B",
    "title": "Heading B"
  }
]

But for the table's data, I want to end up with only one row of data:

var dynamicRow = {};
  
columnData.forEach(function (columnItem) {
  // extract the data set:
  var field = columnItem['class'];
  var value = columnItem['amount'];
  dynamicRow[field] = value;
});
dynamicRows.push(dynamicRow);

Here, I end up with the following:

[
  {
    "A": 2000,
    "B": 3000
  }
]

Now I have the structures I need for my DataTable initialization. The overall script therefore is as follows:

<script type="text/javascript">

var dataSource = [{
  "Name": "PI61890",
  "portfolioName": "PGIM Emerging Markets Debt Local Currency Fund",
  "StartDate": "2020-10-31T00:00:00",
  "EndDate": "2020-10-31T00:00:00",
  "processDate": "2020-10-31T00:00:00",
  "viewDetails": {
    "Name": "Management",
    "Code": "MGMT",
    "category": "Asset",
    "description": "Asset Description",
    "viewClasses": [{
        "class": "A",
        "amount": 2000.0
      },
      {
        "class": "B",
        "amount": 3000.0
      }
    ]
  },
}];

var dynamicColumns = [];
var dynamicRows = [];

function buildDynamicData() {

  var columnData = dataSource[0].viewDetails.viewClasses;
  
  var dynamicRow = {};
  
  columnData.forEach(function (columnItem) {
    // extract the column definitions:
    var dynamicColumn = {};
    dynamicColumn['data'] = columnItem['class'];
    dynamicColumn['title'] = 'Heading ' + columnItem['class'];
    dynamicColumns.push(dynamicColumn);
    
    // extract the data set:
    var field = columnItem['class'];
    var value = columnItem['amount'];
    dynamicRow[field] = value;
  });
  dynamicRows.push(dynamicRow);

}

buildDynamicData();

console.log(dynamicColumns);
console.log(dynamicRows);

  $(document).ready(function() {
  
$('#example').DataTable({
  columns: dynamicColumns,
  data: dynamicRows,
  paging: false,
  info: false
});


  } );

</script>

And the end result looks like this (in my test environment):



来源:https://stackoverflow.com/questions/64242502/jquery-datatable-add-dynamic-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!