把tree结构数据转换easyui的columns
很多时候我们的datagrid需要动态的列显示,那么这个时候我们后台一般提供最直观的数据格式tree结构。那么需要我们前端自己根据这个tree结构转换成easyui的datagrid的columns。那么经过跟后台大神(陈汉军)同事一起的研究最后我整理了一个下面的函数来提供转换。
准备测试数据json
var roots = [ { "title": "监控时间" }, { "title": "不可抗拒标记" }, { "title": "生产设施工况标记", "children": [ { "title": "机组1", "children": [ { "title": "自动" }, { "title": "人工" } ] }, { "title": "机组2", "children": [ { "title": "自动" }, { "title": "人工" } ] } ] }, { "title": "烟尘", "children": [ { "title": "浓度(毫克/立方米)", "children": [ { "title": "实测" }, { "title": "修正值" }, { "title": "折算" }, { "title": "修正折算" }, { "title": "标准" } ] }, { "title": "排放量(千克)", "children": [ { "title": "上报值" }, { "title": "修正值" } ] }, { "title": "自动监测设备维护标记", "children": [ { "title": "自动" }, { "title": "人工" } ] } ] } ] var allLevel = [] //递归获取设置level并且获取最大maxLevel function deepLevel (list, parentNode) { list.forEach(item => { item.level = !parentNode ? 0 : parentNode.level + 1 allLevel.push(item.level) if (item.children && item.children.length > 0) { deepLevel(item.children, item) } }) } // 获取最大层级 function getMaxLevel () { return Math.max.apply(null, allLevel); } // 获取跨列 function getColspan (node) { let colspan = 0 let children = node.children || [] children.forEach(item => { if (item.children && item.children.length > 0) { colspan += getColspan(item) } else { colspan += 1 } }) return colspan } // 获取跨行 function getRowspan (node) { let rowspan = 1 if (!node.children || node.children.length == 0) { rowspan = (getMaxLevel() - node.level + 1) } return rowspan } let field = 0 // 转换数据 function convert (list, parentNode, columns) { list.forEach(item => { item.field = 'field' + field item.rowspan = getRowspan(item) item.colspan = getColspan(item) columns[item.level] = columns[item.level] || [] columns[item.level].push(item) if (item.children && item.children.length > 0) { // item.colspan = item.children.length; convert(item.children, item, columns) } field++ }) } let columns = [] deepLevel(roots) convert(roots, null, columns) console.log(JSON.stringify(columns, null, 4))
var columns=treeToColumns(gridTitle); $('#div1').datagrid({ fit: true, columns: columns })