如何将动态嵌套JSON转为扁平化键值对,在Sencha JS中渲染到HTML
嵌套JSON转扁平化键值对实现方案
你可以通过递归函数实现任意结构嵌套JSON的扁平化转换,原生JS实现无额外依赖,可直接在Sencha JS框架中使用,具体代码如下:
1. 扁平化转换函数
function flattenJson(obj, parentKey = '', result = {}) { for (const key in obj) { if (obj.hasOwnProperty(key)) { // 拼接层级键名,子键首字母大写,与你示例输出格式一致 const newKey = parentKey ? parentKey + key.charAt(0).toUpperCase() + key.slice(1) : key; const currentValue = obj[key]; // 处理嵌套对象:递归遍历 if (typeof currentValue === 'object' && currentValue !== null && !Array.isArray(currentValue)) { flattenJson(currentValue, newKey, result); } // 处理数组:直接转为逗号分隔字符串 else if (Array.isArray(currentValue)) { result[newKey] = currentValue.join(', '); } // 基础类型值:直接赋值 else { result[newKey] = currentValue; } } } return result; }
2. 结合Sencha JS模板使用示例
在调用XTemplate渲染前,先使用上述函数处理原始JSON数据即可:
// 原始嵌套JSON数据 const originData = { "title": "example glossary", "GlossDiv": { "title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "para": "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso": ["GML", "XML"] }, "GlossSee": "markup" } } } }; // 扁平化处理,外层包glossary字段与你要求的输出格式对齐 const processedData = { glossary: flattenJson(originData) }; // 你的原有渲染模板 const renderTpl = new Ext.XTemplate( '<table border="1" cellpadding="10" cellspacing="0">', '<tpl foreach=".">', '<tr>', '<td>{$}</td>', '<td>{.}</td>', '</tr>', '</tpl>', '</table>', { compiled: true } ); // 渲染到指定DOM节点,示例为id为content的节点 renderTpl.overwrite(Ext.get('content'), processedData.glossary);
补充说明
如果需要调整键名拼接规则,比如在层级之间加下划线分隔,只需修改newKey的拼接逻辑即可:
// 调整为下划线分隔格式,示例输出为 GlossDiv_title const newKey = parentKey ? `${parentKey}_${key}` : key;
内容的提问来源于stack exchange,提问作者pt_zg
相关产品推荐
相关产品推荐

