合规国际互联网加速 OSASE为企业客户提供高速稳定SD-WAN国际加速解决方案。 广告
>[info] pid形式数据转children形式 ~~~ /** * pid形式数据转children形式 * @param data 需要转换的数组 * @param idKey id字段名 * @param pidKey pid字段名 * @param childKey 生成的children字段名 * @param pid 顶级的pid * @param addPIds 是否添加所有父级id的字段 * @param parentsKey 所有父级id的字段名称,默认parentIds * @param parentIds 所有父级id * @returns {[]} */ export function toTreeData(data, idKey, pidKey, childKey, pid, addPIds, parentsKey, parentIds) { if (typeof data === 'object' && !Array.isArray(data)) { idKey = data.idKey; pidKey = data.pidKey; childKey = data.childKey; pid = data.pid; addPIds = data.addPIds; parentsKey = data.parentsKey; parentIds = data.parentIds; data = data.data; } if (!idKey) { idKey = 'id'; } if (!pidKey) { pidKey = 'pid'; } if (!childKey) { childKey = 'children'; } if (typeof pid === 'undefined') { pid = []; data.forEach((d) => { let flag = true; for (let i = 0; i < data.length; i++) { if (d[pidKey] == data[i][idKey]) { flag = false; break; } } if (flag) { pid.push(d[pidKey]); } }); } let result = []; data.forEach((d) => { if (d[idKey] == d[pidKey]) { console.error('data error: ', d) return; } if (Array.isArray(pid) ? (pid.indexOf(d[pidKey]) !== -1) : (d[pidKey] == pid)) { let children = toTreeData({ data: data, idKey: idKey, pidKey: pidKey, childKey: childKey, pid: d[idKey], addPIds: addPIds, parentsKey: parentsKey, parentIds: (parentIds || []).concat([d[idKey]]) }); if (children.length > 0) { d[childKey] = children; } if (addPIds) { d[parentsKey || 'parentIds'] = parentIds || []; } result.push(d); } }); return result; } ~~~ ~~~ // 树结构 this.cateList = toTreeData(res.data.data, 'id', 'pid'); ~~~