/**
*
* @param {Object}
* @param {Array} arr 数组对象
* @param {String} childrenKey 子数组的 key
* @param {Number=} expandLevel 可选 开展的层级
* @param {String=} levelKey 可选 树形构造中元素的层级字段 层级从 0 开始 当 expandLevel 有值时 levelKey 为必须
* @param {Boolean=} noParents 返回开展数组时不蕴含根节点 当 root 为 true 时 level 为必须 否则默认为 1
* @example expandArrayObject({arr, childrenKey[, level, root] })
* @description 递归开展数组对象 默认开展时蕴含父节点
*/
export function expandArrayObject({
arr,
childrenKey,
expandLevel,
levelKey,
noParents
}) {const list = []
let currentLevel = 1
const _level = expandLevel || (noParents && 1)
let parentCode = null
const recursiveExpand = (arr, pCode) => {
parentCode = pCode
if (_level && currentLevel > _level) {return}
Array.isArray(arr) &&
arr.forEach((item) => {currentLevel = item[levelKey] + 1
if (noParents && currentLevel < _level) {recursiveExpand(item[childrenKey])
} else {list.push(item)
recursiveExpand(item[childrenKey])
}
})
}
recursiveExpand(arr, parentCode)
return list
}
/**
*
* @param {Object}
* @param arr 查找数据的元数组
* @param childrenKey 子数组的 key
* @param codeKey 主键 key
* @param code 须要找到的元素的主键值
* @description 依据主键递归查找树形数据中对应的数据
*/
export function getChildrenRecursive({arr, childrenKey, codeKey, code}) {
let result
arr.forEach((item) => {if (item[codeKey] === code) {result = item} else {
getChildrenRecursive({arr: item[childrenKey],
childrenKey,
codeKey,
code
})
}
})
return result
}