|
@@ -0,0 +1,86 @@
|
|
|
+module.exports = {
|
|
|
+ /**
|
|
|
+ * 转换数据
|
|
|
+ *
|
|
|
+ * @param {Array} list - 数据库查找的数据
|
|
|
+ * @param {Boolean} tree - 是否展示为树形结构
|
|
|
+ * @param {String} id - id属性名
|
|
|
+ * @param {String} pid - pid属性名
|
|
|
+ * @return {Object} - 返回转换后的数据
|
|
|
+ */
|
|
|
+ convertData(list, tree = true, id, pid) {
|
|
|
+ const rootData = [];
|
|
|
+ const childData = {};
|
|
|
+ let listData = [];
|
|
|
+ for (const tmp of list) {
|
|
|
+ if (tmp[pid] === 0 || tmp[pid] === -1) {
|
|
|
+ rootData.push(tmp);
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ if (childData[tmp[pid]] === undefined) {
|
|
|
+ childData[tmp[pid]] = [];
|
|
|
+ }
|
|
|
+ childData[tmp[pid]].push(tmp);
|
|
|
+ }
|
|
|
+ // 递归组织数据
|
|
|
+ if (tree) {
|
|
|
+ this._recursionTreeData(rootData, childData, id);
|
|
|
+ } else {
|
|
|
+ this._recursionData(rootData, childData, listData, id);
|
|
|
+ }
|
|
|
+
|
|
|
+ return tree ? rootData : listData;
|
|
|
+ },
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 递归组织数组结构数据
|
|
|
+ *
|
|
|
+ * @param {Array} parent - 父节点
|
|
|
+ * @param {Object} childData - 子元素(以pid为key的对象)
|
|
|
+ * @param {Array} outputData - 处理后的数据
|
|
|
+ * @param {String} id - id属性名
|
|
|
+ * @return {void}
|
|
|
+ */
|
|
|
+ _recursionData(parent, childData, outputData = [], id) {
|
|
|
+ for (const index in parent) {
|
|
|
+ // 父节点先进数组
|
|
|
+ outputData.push(parent[index]);
|
|
|
+ // 判断是否存在子项
|
|
|
+ if (childData[parent[index][id]] !== undefined) {
|
|
|
+ // 子项作为父节点递归查找子项中是否还有子项
|
|
|
+ const tmpParent = childData[parent[index][id]];
|
|
|
+ // 已用的子项删除
|
|
|
+ delete childData[parent[index][id]];
|
|
|
+ // 递归元素
|
|
|
+ this._recursionData(tmpParent, childData, outputData);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ },
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 递归组织树结构数据
|
|
|
+ *
|
|
|
+ * @param {Array} parent - 父节点
|
|
|
+ * @param {Object} childData - 子元素(以pid为key的对象)
|
|
|
+ * @param {String} id - id属性名
|
|
|
+ * @return {void}
|
|
|
+ */
|
|
|
+ _recursionTreeData(parent, childData = {}, id) {
|
|
|
+ if (Object.keys(childData).length <= 0) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ for (const index in parent) {
|
|
|
+ // 判断是否存在子项
|
|
|
+ if (childData[parent[index][id]] !== undefined) {
|
|
|
+ // 子项作为父节点递归查找子项中是否还有子项
|
|
|
+ const tmpParent = childData[parent[index][id]];
|
|
|
+ // 已用的子项删除
|
|
|
+ delete childData[parent[index][id]];
|
|
|
+
|
|
|
+ this._recursionTreeData(tmpParent, childData);
|
|
|
+ // 递归完赋值回原数据
|
|
|
+ parent[index].children = tmpParent;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|