首页 > 解决方案 > 渲染数据时如何排除特定的 JSON 对象

问题描述

我有一个包含 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
         ...

标签: javascriptjqueryjsonobjectdatatable

解决方案


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

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


推荐阅读