/** * 集合工具类 */ export default class CollectionUtil { /** * 分组操作 * @param list 要分组的数据 * @param groupHandle 分组的字段或方法 */ public static group (list: Array, groupHandle: string | Function): Map> { const result: Map> = new Map() list.forEach(item => { let value: string = this.getValue(item, groupHandle) const getValue: Array| undefined = result.get(value) if (getValue) { getValue.push(item) } else { result.set(value, [item]) } }) return result } /** * list转map * @param keyHandle key * @param valueHandle value */ public static listToMap(list: Array, keyHandle: string | Function, valueHandle: string | Function): Map { const result = new Map() list.forEach(item => { const key = this.getValue(item, keyHandle) const value = this.getValue(item, valueHandle) result.set(key, value) }) return result } /** * map转object * @param map map */ public static mapToObject(map: Map): any { const result: any = {} map.forEach((value, key) => { result[key] = value }) return result } /** * 分割数据 * @param list 数组 * @param cotNum 分割数 */ public static cutList (list: Array, cotNum: Number): Array> { if (list.length <= cotNum) { return [list] } const result: Array> = [] let num = 0 list.forEach(item => { if (num == 0) { result.push([]) } result[result.length - 1].push(item) num ++ // 重启一行 if (num === cotNum) { num = 0 } }) return result } /** * 获取值 * @param item 对象 * @param handle */ private static getValue (item: any, handle: string | Function): any { if (typeof handle === 'function') { return handle(item) } else { return item[handle] } } }