呈现数据时如何排除特定的JSON对象

时间:2019-02-19 22:19:48

标签: javascript jquery json object datatable

我有一个包含JSON对象的本地JSON文件,我想要它,以便如果obj 包含一个特定的字符串,则该对象将呈现到表中。如果不是,则不渲染。暂时,我在DevTools中遇到一个错误:Uncaught TypeError: Cannot read property 'DT_RowId' of undefined,并且我正在使用DataTables ---尽管它很有用,但使用函数却令人头疼。

JS代码段:

function loadPH() {
    let admissText = admissData.d.results.map(function(val) {
        if (val.p_h_v !== "") { // If this is not empty, then return
            return {
                "PHV": val.p_h_v,
                "Part C": val.partc
            }
        }
    })

    $('#prohac-table').DataTable({
        columns: [
            { data: "PHV" },
            { data: "Part C" },
            ... // ---------- the rest contains irrelevant data

JSON代码段:

{
    "d": {
      "results": [
        {
         ...
         "p_h_v": "" // ------------ this doesn't meet conditions, isn't rendered
         ...
        },
        {
         "p_h_v": "Yes" // ---------- meets conditions---this obj rendered
         ...

2 个答案:

答案 0 :(得分:1)

我认为Array.filter()是您在这里寻找的东西

const admissText = admissData.d.results.filter(result => result.p_h_v !== '');

答案 1 :(得分:1)

将您的示例转换为stack-snippet,只花费了filter,映射未返回的值就是您数据集中的undefined个对象,并引起了问题。 / p>

var admissData = {
  "d": {
    "results": [{
        "p_h_v": "Maybe", // ---------- meets conditions---this obj rendered
        "partc": "show this too"
      },
      {
        "p_h_v": "", // ------------ this doesn't meet conditions, isn't rendered
        "partc": "test - no show"
      },
      {
        "p_h_v": "Yes", // ---------- meets conditions---this obj rendered
        "partc": "test - show"
      }
    ]
  }
};

function loadProHac() {
  let admissText = admissData.d.results
    .filter(x => x.p_h_v !== "")  //added your filter here.
    .map(function(val) {
      return {
        "PHV": val.p_h_v,
        "Part C": val.partc
      }
    });

  $('#prohac-table').DataTable({
    data: admissText,
    columns: [{
        data: "PHV"
      },
      {
        data: "Part C"
      }
    ]
  });
}
loadProHac();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<table id='prohac-table'></table>