首页 > 解决方案 > 如何将分号分隔的数据转换为 DataTable 单元格中的单独行

问题描述

我在 JSON 文档中有一个数组。以下是该数组中的一项:

{
    "generalSolution": "Cloud",
    "generalOperator": "MTN",
    "genericCountry": "USA",
    "vnfProductName": "vEPG;vSAPC;vSGSN-MME",
    "vnfRelease": "2.4;1.3;v1.2399999",
    "vnfVendor": "Ericsson;Ericsson;Ericsson"
}

我想将 DataTables 中的数据显示为一行,如下所示:

在此处输入图像描述

请注意,vnf 详细信息 ( vnfProductName, vnfRelease, vnfVendor) 可以具有可变数量的条目。

标签: javascriptjquerydatatables

解决方案


只需替换;为。<br>String#replace

这是一个例子。在这里,原始对象被更改。如果需要,请考虑调整 id。

$(document).ready(() => {
  const obj = {
    "generalSolution": "Cloud",
    "generalOperator": "MTN",
    "genericCountry": "USA",
    "vnfProductName": "vEPG;vSAPC;vSGSN-MME",
    "vnfRelease": "2.4;1.3;v1.2399999",
    "vnfVendor": "Ericsson;Ericsson;Ericsson"
  };

  for (let key in obj) {
    // Here!
    obj[key] = obj[key].replace(/;/g, '<br>');
  }
  
  $('#dt').DataTable({
    data: [obj],
    columns: [
      {data: 'generalSolution'},
      {data: 'generalOperator'},
      {data: 'genericCountry'},
      {data: 'vnfProductName'},
      {data: 'vnfRelease'},
      {data: 'vnfVendor'}
    ]
  });
});
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

<table id="dt">
  <thead>
    <tr>
      <th>generalSolution</th>
      <th>generalOperator</th>
      <th>genericCountry</th>
      <th>vnfProductName</th>
      <th>vnfRelease</th>
      <th>vnfVendor</th>
    </tr>
  </thead>
</table>


推荐阅读