【问题标题】:How to exclude specific JSON objects when rendering data渲染数据时如何排除特定的 JSON 对象
【发布时间】:2019-02-19 22:19:48
【问题描述】:

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

JS sn-p:

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 sn-p:

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

【问题讨论】:

  • 你能在 stacksn-ps 演示这个问题吗?见stackoverflow.com/help/mcve.map() 并非设计用于过滤来自 Array 的元素。 'DT_RowId' 没有出现在问题的代码中。

标签: javascript jquery json object datatable


【解决方案1】:

将您的示例转换为stack-snippet,只需要filter,map 未返回的值是您的数据集中的undefined 对象并导致了问题。

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>

【讨论】:

  • 做到了。谢谢!我可以从中得到两个收获:1. 我走在了正确的道路上,我的代码需要调整,2..map 在那里而不是.filter(我之前有过...不知道为什么我删除它)应该是一个线索。
【解决方案2】:

我认为Array.filter() 是您在此处寻找的内容:

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

【讨论】:

  • 是的...我之前有过滤器,但出于某种原因将其更改为映射。今晚晚些时候会试试这个。
猜你喜欢
  • 2018-07-15
  • 2021-07-24
  • 1970-01-01
  • 2020-05-27
  • 2021-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-12
相关资源
最近更新 更多