Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

一个面试题,根据json结构生成html表格

我的输入是

{
    A1: {
        B1: {
            C1: {
                D1: 1233,
                D2: 11
            },
            C2: {
                D1: 10,
                D2: 10
            }
        },
        B2: {
            C1: {
                D1: 10,
                D2: 11
            },
            C2: {
                D1: 10,
                D2: 10
            },
            C3: {
                D1: 10,
                D2: 10
            }
        }
    }
}

用什么框架都可以,只要求输出以下table, json的最后一个节点就是table的最后一个column,并且只能占据一行,也就是rowspan要为1.然后难点在于怎么判断前面的column占用的rowspan,我一点思路的都没有囧...

image

更新:
如果有代码演示最好了,底下评论的朋友谢谢了,我看了文章还是想不出来改怎么写代码...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

树的递归,根据后代叶子节点数量决定当前节点所跨的行,深度优先适合此场景。
代码实现:http://jsrun.net/AXaKp/edit

function getRows (data) {
    const result = []
    const values = Object.values(data)
    if (values.some(v => typeof v !== 'object' || !v || !Object.keys(v).length)) {
        result.push([{
            text: Object.keys(data).join(', '),
            rowspan: 1
        }])
        return result
    }
    for (let k in data) {
        const pathList = getRows(data[k])
        if (pathList.length) {
            const first = pathList[0]
            first.unshift({
                text: k,
                rowspan: pathList.length
            })
        }
        result.push(...pathList)
    }
    return result
}

function generateHtml (rows, head) {
    return `
    <table border="1">
        <tr>
          ${ head.map(h => `<th>${h}</th>`).join('') }
        </tr>
        ${rows.map(r => {
            return `
            <tr>
                ${r.map(({ text, rowspan }) => `<td rowspan="${rowspan}">${text}</td>`).join('')}
            </tr>
            `
        }).join('
')}
    </table>
    `
}

function render (data) {
    const rows = getRows(data)
    const head = (rows[0] || []).map(r => `Column-${r.text[0]}`)
    const html = generateHtml(rows, head)
    const div = document.createElement('div')
    div.innerHTML = html
    document.body.appendChild(div)
}

测试:

render(data)

效果:

image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...