arrayOperation.ts 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. * @Author: wanglj 471442253@qq.com
  3. * @Date: 2023-07-11 14:13:56
  4. * @LastEditors: wanglj
  5. * @LastEditTime: 2023-07-20 16:22:10
  6. * @Description: file content
  7. * @FilePath: \labsop_meno\frontend\packages\vue-next-admin\src\utils\arrayOperation.ts
  8. */
  9. /**
  10. * 判断两数组字符串是否相同(用于按钮权限验证),数组字符串中存在相同时会自动去重(按钮权限标识不会重复)
  11. * @param news 新数据
  12. * @param old 源数据
  13. * @returns 两数组相同返回 `true`,反之则反
  14. */
  15. export function judementSameArr(newArr: unknown[] | string[], oldArr: string[]): boolean {
  16. const news = removeDuplicate(newArr);
  17. const olds = removeDuplicate(oldArr);
  18. let count = 0;
  19. const leng = news.length;
  20. for (let i in olds) {
  21. for (let j in news) {
  22. if (olds[i] === news[j]) count++;
  23. }
  24. }
  25. return count === leng ? true : false;
  26. }
  27. /**
  28. * 判断两个对象是否相同
  29. * @param a 要比较的对象一
  30. * @param b 要比较的对象二
  31. * @returns 相同返回 true,反之则反
  32. */
  33. export function isObjectValueEqual<T>(a: T, b: T): boolean {
  34. if (!a || !b) return false;
  35. let aProps = Object.getOwnPropertyNames(a);
  36. let bProps = Object.getOwnPropertyNames(b);
  37. if (aProps.length != bProps.length) return false;
  38. for (let i = 0; i < aProps.length; i++) {
  39. let propName = aProps[i];
  40. let propA = a[propName];
  41. let propB = b[propName];
  42. if (!b.hasOwnProperty(propName)) return false;
  43. if (propA instanceof Object) {
  44. if (!isObjectValueEqual(propA, propB)) return false;
  45. } else if (propA !== propB) {
  46. return false;
  47. }
  48. }
  49. return true;
  50. }
  51. /**
  52. * 数组、数组对象去重
  53. * @param arr 数组内容
  54. * @param attr 需要去重的键值(数组对象)
  55. * @returns
  56. */
  57. export function removeDuplicate(arr: EmptyArrayType, attr?: string) {
  58. if (!Object.keys(arr).length) {
  59. return arr;
  60. } else {
  61. if (attr) {
  62. const obj: EmptyObjectType = {};
  63. return arr.reduce((cur: EmptyArrayType[], item: EmptyArrayType) => {
  64. obj[item[attr]] ? '' : (obj[item[attr]] = true && item[attr] && cur.push(item));
  65. return cur;
  66. }, []);
  67. } else {
  68. return [...new Set(arr)];
  69. }
  70. }
  71. }
  72. export function handleTree(data:[], id = 'id', parentId = 'parentId', children = 'children', rootId = 0) {
  73. //对源数据深度克隆
  74. const cloneData = JSON.parse(JSON.stringify(data))
  75. //循环所有项
  76. const treeData = cloneData.filter(father => {
  77. let branchArr = cloneData.filter(child => {
  78. //返回每一项的子级数组
  79. return father[id] === child[parentId]
  80. });
  81. branchArr.length > 0 ? father[children] = branchArr : '';
  82. //返回第一层
  83. return father[parentId] == rootId;
  84. });
  85. return treeData != '' ? treeData : data;
  86. }