【问题标题】:Datatables returning formatted json data with javascript functions使用 javascript 函数返回格式化 json 数据的数据表
【发布时间】:2019-05-23 16:05:14
【问题描述】:

使用带有 .json 源文件的数据表,我试图在数据显示在表中之前对其进行操作。在此示例中,我试图简单地删除空格并替换为破折号。

据我所知,有两种方法可以进行一些数据操作。一个是 columnDefs,另一个是使用 dataSrc 并返回数据。当我尝试使用 .split 或 .replace 甚至 .toLowerCase()...

例如,我像这样添加了 columnDefs:

 columnDefs: [
            {
                "render": function ( data, type, row ) {
                  console.log(data);
                  var cn = data.split(" ").join("-").toLowerCase();
                  return cn;
                },
                "targets": 1
            }
        ],

控制台显示:

Uncaught TypeError: data.split is not a function

我们如何通过替换等操作数据?

我的数据如下:

{
    "Licensee": "Whistles for Woods",
    "Contact Name": "Bob",
    "Street": "2230 Trail",
    "Suite / PO Box": 0,
    "City": "Alturas",
    "ST": "CA",
    "Zip Code": 997733,
    "Telephone": 0,
    "Email Address": "bobc@email.com",
    "Website Address": "www.domain.com",
    "Fax": "No fax",
    "Products": "whistle with custom logo",
    "Categories": "Miscellaneous"
  },

【问题讨论】:

  • 您的数据是如何格式化的?如果数据值不是字符串或数组,则它不会具有您提到的功能。您可能必须执行更深入的数据操作才能达到您想要的效果。
  • @MichaelSorensen 感谢您的评论。我把它加进去了。它是一个字符串。
  • 啊……你让我想到了!尝试 console.log(typeof data) 告诉我大多数项目都是字符串,但是,那里有一个数字......我做了 data.toString() 现在我可以操作它了......我没有不认为这是必要的,但是,这是一个很好的检查,因为这并不总是干净的数据......
  • 不错!我正要建议大声笑。在这种情况下,我会做一个类似if(typeof data === 'string'){ //do split and join } 的 if 语句,然后继续我的一天 :)

标签: javascript json datatables


【解决方案1】:

如 cmets 中所述

我们只是想确保我们确实在操作字符串而不是任何其他数据类型。因此,在这种情况下,我们将代码更改为如下所示:

 columnDefs: [
        {
            "render": function ( data, type, row ) {
              if(typeof data === 'string'){ 
                  //only if string manipulate
                  data = data.split(" ").join("-").toLowerCase();
              }
              // OR data = data.toString(); whichever is more convenient!
              return data;
            },
            "targets": 1
        }
    ],

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-08
    • 2011-06-11
    • 1970-01-01
    • 2017-02-24
    • 2022-10-20
    • 2018-01-12
    • 2014-09-04
    • 1970-01-01
    相关资源
    最近更新 更多