/** *去除数组中的无效值 * * @export * @param {any[]} array 要检查的数组 * @return {*} [] */ export function validArray(array) { return array.filter(Boolean) } /** *数组对象去重 * * @export * @param {any[]} array 要去重的数组 * @param {string} key 要去重的对象属性值 * @return {*} {any[]} */ export function uniqueArrayObject(array, key) { return array.reduce((pre, cur) => { const keys = pre.map((item) => item[key]) return keys.includes(cur[key]) ? pre : [...pre, cur] }, []) } export function filterQueryList(array, key = 'value') { return array.filter((item) => item[key]) } /** *数组去重 * * @export * @param {any[]} array 要检查的数组 * @return {*} [] */ export function uniqueArr(array) { return Array.from(new Set(array)) } export function nest2tile(arr, childrenKey, obtainChildren) { if (!childrenKey) { childrenKey = 'children' } if (!arr || arr.constructor !== Array) return return [].concat( ...arr.map((item) => { let _item = { ...item } if (obtainChildren == undefined || obtainChildren == false) { delete _item[childrenKey] } return [].concat(_item, ...nest2tile(item[childrenKey] || [])) }) ) } // 平铺结构转嵌套结构 export function tile2nest(array, key, pKey, childrenKey) { if (!array || array.constructor !== Array) { return array } // 复制一份,避免修改原始数组 let ary = [...array] key = key || 'id' pKey = pKey || 'parentId' childrenKey = childrenKey || 'children' // 定义一个待移除数组 let ary2remove = [] ary.map((item) => { if (item[key] !== item[pKey]) { // 找父节点 let p = ary.filter((c) => c[key] === item[pKey]) if (p && p.length == 1) { p[0][childrenKey] = p[0][childrenKey] || [] // 将子节点放到父节点中 p[0][childrenKey].push(item) ary2remove.push(item[key]) } } }) // 遍历移除待删除对象 ary2remove.map((item) => { ary = ary.filter((c) => c[key] !== item) }) return ary }