【问题标题】:How do I fix this JSON object to html table code?如何将此 JSON 对象修复为 html 表格代码?
【发布时间】:2013-05-02 20:45:43
【问题描述】:

我一直在修改我找到的一段代码,但我无法让它按我想要的方式工作。这是当前的 Javascript:

function JsonUtil() {
    /**
     * Given a provided object,
     * return a string representation of the object type.
     */
    this.isType = function (obj_) {
        if (obj_ === null) {
            return "null";
        }
        if (obj_ === NaN) {
            return "Nan";
        }
        var _type = typeof obj_;
        switch (_type) {
        case "undefined":
            return "undefined";
        case "number":
            return "number";
        case "boolean":
            return "boolean";
        case "string":
            return "string";
        case "function":
            return "function";
        case "object":
            if (this.isArray(obj_)) {
                return "array";
            }
            return "associative";
        }
    },
    /**
     * Recursively search and display array as an HTML table.
     */
    this.tableifyArray = function (array_) {
        if (array_.length === 0) {
            return "[ empty ]";
        }

        var _out = "<table class='arrayTable'>";  

        for(var i = 0; i < array_.length; i++) {
            _out += "<tr class='arrayTr'><td class='arrayTd'>"
                 + this.tableifyObject(array_[i]) + "</td></tr>";
        }
        _out += "</table>";
        return _out;
    },
    /**
     * Recursively search and display common javascript types as an HTML table.
     */
    this.tableifyObject = function (obj_) {
        /*
   if (obj_ === '') {
        return "[ empty ]";
     }
     */
        switch (this.isType(obj_)) {
        case "null":
            return "¡The data object is null!";
        case "undefined":
            return "undefined";
        case "number":
            return obj_;
        case "boolean":
            return obj_;
        case "string":
            return obj_;
        case "array":
            return this.tableifyArray(obj_);
        case "associative":
            return this.tableifyAssociative(obj_);
        }
        return "!error converting object!";
    },
    /**
     * Recursively search and display associative array as an HTML table.
     */
    this.tableifyAssociative = function (array_) {
        if (this.isEmpty(array_)) {
            return "{ empty }";
        }

        var _out = "<table class='associativeTable'>";

        for (var _index in array_) {
            _out += "<tr class='associativeTr'><td class='associativeTd'>"
                + this.tableifyObject(_index) + "</td><td class='associativeTd'>"
                + this.tableifyObject(array_[_index]) + "</td></tr>";
        }
        _out += "</table>";
        return _out;
    },
    /**
     * identify if an associative array is empty
     */
    this.isEmpty = function (map_) {
        for (var _key in map_) {
            if (map_.hasOwnProperty(_key)) {
                return false;
            }
        }
        return true;
    },
    /**
     * Identify is an array is a 'normal' (not associative) array
     */
    this.isArray = function (v_) {
        return Object.prototype.toString.call(v_) == "[object Array]";
    },
    /**
     * given the desire to populate a map of maps, adds a master key,
     * and child key and value to a provided object.
     */
    this.addToMapOfMaps = function (map_, mkey_, key_, value_) {
        if (map_ === undefined) {
            map_ = {};
        }
        if (map_[mkey_] === undefined) {
            map_[mkey_] = {}
        }
        if (map_[mkey_][key_] === undefined) {
            map_[mkey_][key_] = null;
        }
        map_[mkey_][key_] = value_;
        return map_;
    }
}

这是它的 CSS:

 .arrayTable { border: 1px solid #c2c2c2; background-color: #c2c2c2; padding: 5px;}
 .arrayTr { border: 1px solid #c2c2c2; background-color: #c2c2c2; padding: 5px;}
 .arrayTd { border: 1px solid #c2c2c2; background-color: #c2c2c2; padding: 5px; vertical-align: top;}
 .associativeTable { border: 1px solid #c2c2c2; background-color: #fff; padding: 5px;}
 .associativeTr { border: 1px solid #c2c2c2; background-color: #fff; padding: 5px;}
 .associativeTd { border: 1px solid #c2c2c2; background-color: #eee; padding: 5px; vertical-align: top;}

打电话给你只需这样做:

var json = new JsonUtil();
json.tableifyObject(jsonObject);

效果非常好,但不是我想要的,目前数组表显示如下:

NAME 123123
ID 1
CATEGORY 12412

NAME AAAA
ID 2
CATEGORY 2123

我想修改数组表的显示方式,需要它们垂直并且所有数据都在一个表结构中,而不是每个寄存器中的很多表。像这样:

NAME ID CATEGORY
123123 1 12412
AAAA 2 2123

我需要如何更改递归 Javascript 才能创建这样的结果?

【问题讨论】:

  • 移动&lt;tr&gt;&lt;/tr&gt; 以包裹for( .. in .. ) 循环,从而在单行中迭代&lt;td&gt;,然后重复。
  • 这是如何工作的:if (obj_ === NaN) { return "Nan"; } 即使NaN === NaNfalse?认为应该使用isNaN()
  • @MackieeE 我试过了,但得到了另一个结果。 Paul Grime,是的,不知道为什么代码包含它,将删除它。我正在用这个来融化我的大脑哈哈哈:/
  • 有人帮忙吗?我不能让它工作:/

标签: javascript html json recursion html-table


【解决方案1】:

成功了,伙计们!如果 _obj 是数组,则添加代码以生成另一种类型的表。 以防万一有人需要同样的东西,这很好用!

function createTableBasedOnJsonArray(array_) {

    var _out = "";      
    for(var index in array_) {
        if(index == 0) {
            _out += "<table class='arrayTable'><thead>";
            //create thead
            for(var key in array_[0]) {
                _out += "<th>" + key + "</th>";
            }
            _out += "</thead>";
        }
        var values = array_[index];     
        //create tbody
        _out += "<tbody><tr class='arrayTr'>";
        for(var key in values) {
            _out += "<td class='arrayTd'>" + values[key] + "</td>";
        }
        _out += "</tr>";
    }
    _out += "</tbody></table>"
    return _out;
}

所以 JSON 对象到 HTML 的整个 json 库现在如下:

function JsonUtil() {
    /**
     * Given a provided object,
     * return a string representation of the object type.
     */
    this.isType = function (obj_) {
        if (obj_ === null) {
            return "null";
        }
        var _type = typeof obj_;
        switch (_type) {
        case "undefined":
            return "undefined";
        case "number":
            return "number";
        case "boolean":
            return "boolean";
        case "string":
            return "string";
        case "function":
            return "function";
        case "object":
            if (this.isArray(obj_)) {
                return "array";
            }
            return "associative";
        }
    },
    /**
     * Recursively search and display array as an HTML table.
     */
    this.tableifyArray = function (array_) {
        if (array_.length === 0) {
            return "[ empty ]";
        }

        var _out = createTableBasedOnJsonArray(array_);

        return _out;
    },
    /**
     * Recursively search and display common javascript types as an HTML table.
     */
    this.tableifyObject = function (obj_) {
        switch (this.isType(obj_)) {
        case "null":
            return "¡The data object is null!";
        case "undefined":
            return "undefined";
        case "number":
            return obj_;
        case "boolean":
            return obj_;
        case "string":
            return obj_;
        case "array":
            return this.tableifyArray(obj_);
        case "associative":
            return this.tableifyAssociative(obj_);
        }
        return "!error converting object!";
    },
    /**
     * Recursively search and display associative array as an HTML table.
     */
    this.tableifyAssociative = function (array_) {
        if (this.isEmpty(array_)) {
            return "{ empty }";
        }

        var _out = "<table class='associativeTable'>";

        for (var _index in array_) {
            _out += "<tr class='associativeTr'><td class='associativeTd'>"
                + this.tableifyObject(_index) + "</td><td class='associativeTd'>"
                + this.tableifyObject(array_[_index]) + "</td></tr>";
        }
        _out += "</table>";
        return _out;
    },
    /**
     * identify if an associative array is empty
     */
    this.isEmpty = function (map_) {
        for (var _key in map_) {
            if (map_.hasOwnProperty(_key)) {
                return false;
            }
        }
        return true;
    },
    /**
     * Identify is an array is a 'normal' (not associative) array
     */
    this.isArray = function (v_) {
        return Object.prototype.toString.call(v_) == "[object Array]";
    },
    /**
     * given the desire to populate a map of maps, adds a master key,
     * and child key and value to a provided object.
     */
    this.addToMapOfMaps = function (map_, mkey_, key_, value_) {
        if (map_ === undefined) {
            map_ = {};
        }
        if (map_[mkey_] === undefined) {
            map_[mkey_] = {}
        }
        if (map_[mkey_][key_] === undefined) {
            map_[mkey_][key_] = null;
        }
        map_[mkey_][key_] = value_;
        return map_;
    }
}

function createTableBasedOnJsonArray(array_) {

    var _out = "";      
    for(var index in array_) {
        if(index == 0) {
            _out += "<table class='arrayTable'><thead>";
            //create thead
            for(var key in array_[0]) {
                _out += "<th>" + spaceRawKeyName(key).toUpperCase() + "</th>";
            }
            _out += "</thead>";
        }
        var values = array_[index];     
        //create tbody
        _out += "<tbody><tr class='arrayTr'>";
        for(var key in values) {
            _out += "<td class='arrayTd'>" + values[key] + "</td>";
        }
        _out += "</tr>";
    }
    _out += "</tbody></table>"
    return _out;
}

如果有人对“spaceRawKeyName”函数感兴趣,该函数用于通过大写锁定识别将这个accountId这样的字符串分隔到account_Id。

function spaceRawKeyName(string) {  
    var newone = [];
    for(i=0; i<string.length;i++) {
        character = string.charAt(i);
        if(character == character.toUpperCase()) {
            newone.push("_");
        }
        newone.push(character);     
    }
    var text = "";
    for(i=0;i < newone.length;i++){
        text += newone[i];
    }
    return text;
} 

当然,您可以稍后创建一个 .toUpperCase() 以使其看起来更花哨 ACCOUNT_ID,顺便说一句...如果您不想添加“_”,您可以简单地将其替换为空格。

【讨论】:

  • @MackieeE 是的 :) 谢谢!!我花了 15 分钟才想到这个功能,哈哈,但我必须先跟进代码。
猜你喜欢
  • 2020-01-12
  • 2020-06-13
  • 2017-09-14
  • 2021-07-23
  • 2013-12-26
  • 2018-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多