We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
老师你好,希望增加json转树形结构,我简单修改了下源码,暂时实现了如下效果:
输入:
id name pid 1 aa 0 2 bb 0 3 cc 0 4 dd 0 5 ee 1 6 a0 1 7 a1 1 8 a2 2 9 a3 2 10 a4 3 11 a5 3 12 a6 4
根据配置的id,pid生成json树 部分代码如下:
const data = JSON.parse(this.outputText); // 获取id,pid,childen的值 从form表单获取 const id = $("#setId").val(); const pid = $("#setPid").val(); const children = $("#setChildren").val(); const config = { id, pid, children, }; const treeData = dataToTree(data, config); this.outputTextArea.val(JSON.stringify(treeData, null, 2)); /** * dataToTree * @param {*} data * @param {*} config * @returns */ function dataToTree(data, config) { const { id, pid, children } = config; const result = []; let keyObj = {}; data.forEach((item) => { keyObj[item[id]] = item; }); data.forEach((item) => { let parent = keyObj[item[pid]]; if (parent) { if (!parent[children]) { parent[children] = []; } parent[children].push(item); } else { result.push(item); } }); return result; }
最后的生成结果:
[ { "id": 1, "name": "aa", "pid": 0, "children": [ { "id": 5, "name": "ee", "pid": 1 }, { "id": 6, "name": "a0", "pid": 1 }, { "id": 7, "name": "a1", "pid": 1 } ] }, { "id": 2, "name": "bb", "pid": 0, "children": [ { "id": 8, "name": "a2", "pid": 2 }, { "id": 9, "name": "a3", "pid": 2 } ] }, { "id": 3, "name": "cc", "pid": 0, "children": [ { "id": 10, "name": "a4", "pid": 3 }, { "id": 11, "name": "a5", "pid": 3 } ] }, { "id": 4, "name": "dd", "pid": 0, "children": [ { "id": 12, "name": "a6", "pid": 4 } ] } ]
The text was updated successfully, but these errors were encountered:
No branches or pull requests
老师你好,希望增加json转树形结构,我简单修改了下源码,暂时实现了如下效果:
输入:
根据配置的id,pid生成json树
部分代码如下:
最后的生成结果:
The text was updated successfully, but these errors were encountered: