70 lines
1.8 KiB
JavaScript
70 lines
1.8 KiB
JavaScript
|
|
/**
|
|||
|
|
* 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 (!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])
|
|||
|
|
}
|
|||
|
|
})
|
|||
|
|
}
|
|||
|
|
const 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)) {
|
|||
|
|
const 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
|
|||
|
|
}
|