对象拷贝
/**
* @param {Object} source
* @returns {Object}
*/
export function deepClone(source) {
if (!source && typeof source !== 'object') {
throw new Error('error arguments', 'deepClone')
}
const target = source.constructor === Array ? [] : {}
Object.keys(source).forEach(keys => {
if (source[keys] && typeof source[keys] === 'object') {
target[keys] = deepClone(source[keys])
} else {
target[keys] = source[keys]
}
})
return target
}
列表构建树
/**
* @param {Array} arr
* @param {String} pid
* @param {String} id
* @param {Number | String} footer
* @returns {Array}
*/
function buildListToTree(arr,pid = 'pid',id = 'id',footer = 0){
var copy = JSON.parse(JSON.stringify(arr))
function buildLeafs(arr){
return arr.map(element => {
element.children = copy.filter(ele=>ele[pid] == element[id])
element.children.length && buildLeafs(element.children)
return element
})
}
return buildLeafs(copy.filter(ele=>ele[pid] == footer))
}
树过滤
/**
* @param {Array} tree
* @returns {Array}
*/
function filterTree(tree){
return tree.filter(element=>{
if(judgeFunc(element)){
if(element.children && element.children.length > 0){
element.children = filterTree(element.children)
}
return element
}else{
return false
}
})
}