我的工作中常用的业务函数

74 阅读5分钟

1 701项目用过

公司常用,全部字典根据类型,筛选某个字典

interface RootObject {
  id: number;
  description: string;
  code: string;
  enumItems: any;
}

interface RootObjectItem {
  value: string;
  code: string;
}
// 字典arr=全部字典,筛选name某个字典
export const getFindList = (arr: any[] = [], name: string) => {
  const dict =
    (arr &&
      arr.filter((item: RootObject) => {
        return item.code === name;
      })[0]?.itemList) ||
    [];
  const list = dict.map((item: RootObjectItem) => {
    const obj = {
      label: item.value,
      value: item.code,
    };
    return obj;
  });
  return list;
};
// 字典-获取树的单层级
export const getDataSourceList = (arr: any[] = [], object: any) => {
  if (Object.keys(object).length == 0) {
    const list =
      arr &&
      arr.map((item: RootObject3) => {
        const obj = {
          id: item.value,
          name: item.label,
          parentId: null,
        };
        return obj;
      });

    return list || [];
  }
  const list =
    arr &&
    arr.map((item: RootObject3) => {
      const obj = {
        id: item.value,
        name: `${item.label}${object[item.value] || 0})`,
        parentId: null,
      };
      return obj;
    });

  return list || [];
};
// 字典-获取树的多层级
// 多层
export const getFindListTree = (arr: any[] = [], name: string) => {
  const dict =
    (arr &&
      arr.filter((item: RootObject2) => {
        return item.code === name;
      })[0]?.items) ||
    [];
  return dict;
};

//多层 arr=[{id:'1',value:'123',code:'1',childrenNode:[}],object={1,2,3}
export const getDataSourceListTree = (arr: any[] = [], object: any) => {
  if (object) {
    const list = arr.map((item: any) => {
      const arr2: any = {};
      for (const key in object) {
        if (item.code == key) {
          item.childrenNode = [...object[key]];
          arr2.id = `${item.id}`;
          arr2.caName = item.value;
          arr2.childrenNode = item.childrenNode;
        }
        arr2.id = `${item.id}`;
        arr2.caName = item.value;
      }
      return arr2;
    });
    return list;
  }
  const list = arr.map((item: any) => {
    const obj = {
      id: item.value,
      caName: item.value,
      childrenNode: [],
    };
    return obj;
  });
  return list;
};

根据字典的值,筛选出对应的值(name)进行展示,高频率使用

// 字典过滤,data=字典的值code,arr=全部数据的数组
export function getValue(data: string, arr: any[] = []) {
  if (arr.length) {
    let name = '';
    arr.map((item: any) => {
      if (item.value == data) {
        name = item.label;
      }
    });
    return name;
  }
  return '';
}

两个数组取并集第一种:批量添加新数据时,会对比新的数据根据id进行过滤,过滤后的数组需要定义字段名,高频率使用

// 智能分析-需求表格的数据转化,arr=旧数据,newArr=新数据
export const getAnalysisList = (arr: any[] = [], newArr: any[] = []) => {
  // 取并集
  const tempKeys = [];
  for (const item of arr) {
    if (tempKeys.indexOf(item['id']) == -1) {
      tempKeys.push(item['id']);
    }
  }

  for (const item of newArr) {
    let sign = true;
    for (const key of tempKeys) {
      if (key == item['id']) {
        sign = false;
      }
    }
    if (sign) arr.push(item);
  }

  // 重新传化参数
  const list = arr.map((item: any, index: number) => {
    const obj = {
      id: item.id,
      key: index + 1,
      name: item.name,
      goodsType: item.goodsType || item.weaponType,
      analysisCount: item.analysisCount || 0,
      demandCount: item.demandCount || 0,
      feedBackCount: item.feedBackCount || 0,
      minimum: item.minimum || item.minimum || 0,
      canUse: item.canUse || 0,
      goodsTotal: item.goodsTotal || item.weaponTotal,
    };
    return obj;
  });
  return list;
};


两个数组取并集第二种:批量添加新数据时,会对比新的数据根据type变量进行过滤,高频率使用

// 创建任务-目标去重, arr旧数组,newArr新增的数组,type根据关键字去重
export const getReductList = (arr: any[] = [], newArr: any[] = [], type: string) => {
  // 取并集
  const tempKeys = [];
  for (const item of arr) {
    if (tempKeys.indexOf(item[type]) == -1) {
      tempKeys.push(item[type]);
    }
  }

  for (const item of newArr) {
    let sign = true;
    for (const key of tempKeys) {
      if (key == item[type]) {
        sign = false;
      }
    }
    if (sign) arr.push(item);
  }
  return arr;
};

对象的索引值作为变量的写法[name]

// 智能分析-随机智能分析参数数据
export const getAnalysisCount = (arr: any[] = [], name: string, fuel: number, water: number) => {
  const list = arr.map((item: any) => {
    if (item.goodsType === '1') {
      const obj = {
        ...item,
        [name]: fuel?.toFixed(2),
      };
      return obj;
    } else {
      const obj = {
        ...item,
        [name]: water?.toFixed(2),
      };
      return obj;
    }
  });
  return list;
};

data2数组里满足条件的数据,插入到data1数组里
export function findList(data1: any[], data2: any[]) {
  const list = data1.map((item: any) => {
    const installer = data2.realList.find(
      (ele: any) => ele.deviceId == item.id
    );
    if (installer) {
      item.onlineStatus = 1;
      item.startCreateTime = installer.alarmBegin;
    }
    return item;
  });
  return list;
}

2 wrj项目用过

// 数组归类-根据编组号groupNo
export function classify(arr: any) {
  let map: any = {};
  let myArr = [];
  for (let i = 0; i < arr.length; i++) {
    if (!map[arr[i].groupNo]) {
      myArr.push({
        groupNo: arr[i].groupNo,
        data: [arr[i]],
      });
      map[arr[i].groupNo] = arr[i];
    } else {
      for (let j = 0; j < myArr.length; j++) {
        if (arr[i].groupNo === myArr[j].groupNo) {
          myArr[j].data.push(arr[i]);
          break;
        }
      }
    }
  }
  return myArr;
}
// 平台转化为编组,groupNo
export const generateArr = (arr: any) => {
  const map = new Map();
  if (arr?.length) {
    arr.forEach((item: any) => {
      const sign = item.groupNo;
      if (map.has(sign)) {
        const temp = map.get(sign);
        temp.push(item);
        map.set(sign, temp);
      } else {
        map.set(sign, [item]);
      }
    });
  }
  return Object.values(Object.fromEntries(map));
};

上移,下移某个数组里的值

// 上移数据项
const upItem = (item: any) => {
  const index = state.formData.dataItem.indexOf(item);
  swapArray(state.formData.dataItem, index - 1, index, 0);
};

// 下移数据项
const downItem = (item: any) => {
  const index = state.formData.dataItem.indexOf(item);
  swapArray(state.formData.dataItem, index, index + 1, 0);
};

// 数组元素互换位置
export const swapArray = (arr:any, index1:any, index2:any,max:any) => {
    if (index1<max) {
    return ElMessage.error('已在最上面');
  }
  if (index2>=arr.length) {
    return ElMessage.error('已在最下面');
  }

  arr[index1] = arr.splice(index2, 1, arr[index1])[0];
  return arr;
};

// 数组元素互换位置
export const swapArrayPlus = (arr:any, index1:any, index2:any) => {
  if (index1<3) {
  return ElMessage.error('已在最上面');
}
if (index2>=arr.length) {
  return ElMessage.error('已在最下面');
}

arr[index1] = arr.splice(index2, 1, arr[index1])[0];
return arr;
};

保留*位小数,默认两位

// 保留*位小数,默认两位
export function getComFixed(data: number, len = 2) {
  if (data && data >= 0) {
    return data.toFixed(len);
  }
  return '-';
}

数组转化字符串

// 数组转化字符串
export function getJoin(data: any, sty: any = ',') {
  if (data && data.length) {
    return data.join(sty);
  }
}

二维数组转化-一维数组

// 必经点二维数组转化-一维数组
export function getEWList(data: any) {
  if (data && data.length) {
    const list = data.map((item: any) => {
      return { fLat: item[0], fLon: item[1] };
    });
    return list;
  }
}
// 字符串数组一维-转二维
export const erWeiArr = (arr: any) => {
  const res: any = [];
  arr.map((item: any, index: any) => {
    const temp = arr.slice(index * 1, index * 1 + 1);
    res.push(temp);
  });
  return res;
};

// 二维字符串数组转数字数组
export const numberArr = (arr: any) => {
  const res: any = [];
  arr.map((item: any, index: any) => {
    const temp = item[0].split(',');
    res.push(temp);
  });
  return res;
};

时间

// 时间戳转化'YYYY-MM-DD HH:mm:ss'
import moment from 'moment';
export function getMomentData(data: number) {
  if (data) {
    return moment(data).format('YYYY-MM-DD HH:mm:ss');
  }
  return '-';
}
// 格林威治转化'时间戳'
export function getMomentData2(data: number) {
  if (data) {
    return moment(data).toDate().getTime();
  }
  return null;
}

// 时间戳转-中文时分秒
export const formatSecond = (data: any) => {
  const tData = parseInt(data) || 0;
  const minutes = Math.floor(tData / 60);
  const second = tData % 60;
  return `${minutes}${second}秒`;
};

// 时间戳-秒转时分秒
export const secondToHSM = (sData: any) => {
  const h = Math.floor(sData / 3600);
  const minute = Math.floor((sData / 60) % 60);
  const second = Math.ceil(sData % 60);

  const hours = h < 10 ? '0' + h : h;
  const formatSecond = second > 59 ? 59 : second;
  return `${hours > 0 ? `${hours}:` : ''}${minute < 10 ? '0' + minute : minute}:${
    formatSecond < 10 ? '0' + formatSecond : formatSecond
  }`;
};
// 有树结构-有子集的数据的给个标识
export const formatting = (data: any) => {
  const newData = data.map((item: any) => {
    return {
      ...item,
      children: item?.children?.map((pl: any) => ({
        ...pl,
        childrenFlag: true,
      })),
    };
  });
  return newData;
};

// 树结构-字段进行转化2
export const getLableValue2 = (data: any) => {
  const arr: any = [];
  data.map((item: any) => {
    arr.push({
      label: item.name,
      value: item.vmf,
      children: getLableValue2(item.children),
    });
  });
  return arr;
};

// 树转化平层
export const arrTree = (list: any) => {
  const arr: any = [];
  list.forEach((item: any) => {
    arr.push(item);
    item.children && arr.push(...arrTree(item.children));
  });
  return arr;
};

操作文件图片的一些方法

// 文件格式化-加name
export const getName = (arr: any) => {
  const list =
    arr &&
    arr.map((item: any, index: any) => {
      const obj = { ...item, name: item.file_name + "." + item.file_type };
      return obj;
    });
  return list;
};

// 文件转base64
export const getBase64 = (file: any) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
};

// 批量的base64放入一个数组里丢给后端
export const getFileData = (arr: any[]) => {
  return new Promise((resolve, reject) => {
    let list: any = [];
    arr.map(async (file: any) => {
      let res = (await getBase64(file.raw)) as any;
      list.push(res);
      if (list.length === arr.length) {
        resolve(list);
      }
    });
  });
};

// 二进制字符串(类似base64)转文件流 方法一
export function base64ToFile(base64: string, fileName: string, fileType: any) {
  const fileStream = base64;
  // 进行进一步处理,例如将文件流转为文件对象
  const blob = new Blob([fileStream], {
    type: "application/octet-stream",
  });
  const file: any = new File([blob], fileName + "." + fileType, {
    type: fileType,
  });
  return file;
}

// 二进制字符串(类似base64)转文件流 方法二
export function base64ToFile2(base64: any, fileName: any, fileType: any) {
  let bstr = atob(base64);
  let n = bstr.length;
  let u8arr = new Uint8Array(n);

  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], fileName, { type: fileType });
}

// get请求url点击直接下载
export const getExportFile = (url: string) => {
  const link = document.createElement("a"); // 创建一个 a 标签用来模拟点击事件
  link.style.display = "none";
  link.href = url;
  link.setAttribute("download", "文件名");
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};