如何基于json数据重复列以显示数据表 [英] How to repeat the columns based on the json data for datatable display

查看:87
本文介绍了如何基于json数据重复列以显示数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自AJAX响应的JSON数据,它具有嵌套数组.

Hi I have a JSON data coming from AJAX response and it has nested array.

[{
    "Solution": "MobileBroadband",
    "Operator": "MTN",
    "VNF": [{
        "vendor": "vendor1",
        "name": "product1",
        "release": "1.0"
    },
    {
        "vendor": "vendor3",
        "name": "prodc3",
        "release": "3.0"
    },
    {
        "vendor": "saef",
        "name": "vEPG",
        "release": "2.4"
    }]
},
{
    "Solution": "CLoud",
    "Operator": "Airtel",
    "VNF": [{
        "vendor": "vendor1",
        "name": "product1",
        "release": "1.0"
    },
    {
        "vendor": "vendor3",
        "name": "prodc3",
        "release": "3.0"
    }]
}]

如何将以上数据动态添加到数据表的列中.

How can I dynamically add the above data to columns of data table.

我期望这样的事情:

推荐答案

首先,您需要设置DataTables ajax 选项:

First, you would need to set DataTables ajax option accordingly:

$('#mytable').DataTable({
    ajax: {
        ...
        url: '/getdata' //URL to API that returns your JSON data
    }

});

接下来,您需要展平"您的源JSON结构,以便它包含对象数组,其中每个属性对应于表列.为此,您可能需要使用 ajax.dataSrc 选项(对收到的JSON进行后处理):

Next, you need to 'flatten' your source JSON structure, so that it contains array of objects where each property corresponds to table column. For that purpose, you may need to use ajax.dataSrc option (to postprocess received JSON):

$('#mytable').DataTable({
    ajax: {
        url: '/getdata',
        dataSrc: rawJson => rawJson.map(entry => {
            entry.VNF.forEach((vnfEntry, vnfEntryIndex) => Object.entries(vnfEntry).forEach(vnfEntryProp => entry[vnfEntryProp[0] + vnfEntryIndex] = vnfEntryProp[1]));
            delete entry.VNF;
            return entry;
        })
    }
});

最后,您可能希望取消显示有关某些列缺少数据的DataTables警告(因为对于不同的运营商,您有不同数量的NFV供应商):

And finally, you may want to suppress DataTables warning that informs you about missing data for certain columns (as you have different number of NFV vendors for different operators):

$.fn.dataTable.ext.errMode = 'none';

但是您必须谨慎使用该选项,因为它会抑制来自DataTables引擎的所有错误通知.

But you must be carefull with that option as it will suppress all error notifications from DataTables engine.

对于功能完善的 demo ,您可能要查看此链接.

For full-blown demo, you might want to check out this link.

这篇关于如何基于json数据重复列以显示数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆