From 07d361f4983fb2f0d237ca4602f8bd54f5e54f2e Mon Sep 17 00:00:00 2001 From: luowenfeng <1092164058@qq.com> Date: Tue, 19 Jul 2022 11:21:59 +0800 Subject: [PATCH] =?UTF-8?q?feature(uniapp=E5=88=86=E7=B1=BB):=20=E5=88=86?= =?UTF-8?q?=E7=B1=BB=E5=88=97=E8=A1=A8=E4=BB=A5=E5=8F=8A=E5=95=86=E5=93=81?= =?UTF-8?q?=E5=8A=A0=E8=BD=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- yudao-ui-app/utils/tree.js | 59 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 yudao-ui-app/utils/tree.js diff --git a/yudao-ui-app/utils/tree.js b/yudao-ui-app/utils/tree.js new file mode 100644 index 000000000..2be7336ce --- /dev/null +++ b/yudao-ui-app/utils/tree.js @@ -0,0 +1,59 @@ +/** + * 构造树型结构数据 + * @param {*} data 数据源 + * @param {*} id id字段 默认 'id' + * @param {*} parentId 父节点字段 默认 'parentId' + * @param {*} children 孩子节点字段 默认 'children' + * @param {*} rootId 根Id 默认 0 + */ +export function handleTree(data, id, parentId, children, rootId) { + id = id || 'id' + parentId = parentId || 'parentId' + children = children || 'children' + rootId = rootId || Math.min.apply(Math, data.map(item => { + return item[parentId] + })) || 0 + //对源数据深度克隆 + const cloneData = JSON.parse(JSON.stringify(data)) + //循环所有项 + const treeData = cloneData.filter(father => { + let branchArr = cloneData.filter(child => { + //返回每一项的子级数组 + return father[id] === child[parentId] + }); + branchArr.length > 0 ? father.children = branchArr : ''; + //返回第一层 + return father[parentId] === rootId; + }); + return treeData !== '' ? treeData : data; +} + +/** + * 树形结构进行删除深度不够的分支 + * 目前只删除了不够三层的分支 + * 对于高于三层的部分目前不做处理 + * todo 暴力遍历,可用递归修改 + * @param {*} data 树形结构 + */ +export function convertTree(data) { + //对源数据深度克隆 + const cloneData = JSON.parse(JSON.stringify(data)) + // 遍历克隆数据,对源数据进行删除操作 + for (let first = 0; first < cloneData.length; first++) { + for (let second = 0; second < cloneData[first].children.length; second++) { + for (let three = 0; three < cloneData[first].children[second].children.length; three++) { + if (data[first].children[second].children[three].children == undefined || + data[first].children[second].children[three].children === 0) { + data[first].children[second].children.splice(second, 1); + } + } + if (data[first].children[second].children == undefined || data[first].children[second].children === 0) { + data[first].children.splice(second, 1); + } + } + if (data[first].children == undefined || data[first].children.length === 0) { + data.splice(first, 1); + } + } + return data; +}