jsonToTable.js 781 字节
Newer Older
B
update  
baiy 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
import _ from "lodash";
import {beautify} from "../formatter/html";

const convert = (json = [], {header = true} = {}) => {
    if (!_.isArray(json) || json.length < 1) {
        return ""
    }
    let html = ["<table>"];
    let keys = Object.keys(json[0])
    if (header) {
        html.push(
            '<thead>',
            '<tr>',
            ...keys.map((item) => {
                return `<th>${item}</th>`
            }),
            '</tr>',
            '</thead>'
        )
    }
    html.push("<tbody>")
    for (let row of json) {
        html.push("<tr>", ...keys.map((item) => {
            return `<td>${item in row ? row[item] : ""}</td>`
        }), '</tr>');
    }
    html.push("</tbody></table>")
    return beautify(html.join(""))
}

export default convert