我有一个包含 JSON 对象的本地 JSON 文件,我想要它,这样如果一个对象包含一个特定的字符串,那么该对象就会呈现到一个表中。如果不是,那么它不会被渲染。目前我在 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
...
最佳答案
将您的示例转换为 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>
关于javascript - 如何在呈现数据时排除特定的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54775806/