tools.js 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. const tools = {
  2. isNotEmpty: (val) => {
  3. return typeof val !== 'undefined' && val !== null ? true : false
  4. },
  5. isEmpty: (val) => {
  6. return val === null && typeof val === 'undefined' ? true : false
  7. },
  8. isBlack: (val) => {
  9. let regular = new RegExp('^[ ]+$')
  10. return (
  11. val == null || typeof val == 'undefined' || val == '' || regular.test(val)
  12. )
  13. },
  14. data2Tree: (list, topValue, pName, name) => {
  15. if (tools.isEmpty(list) || list.length === 0) {
  16. return list
  17. }
  18. if (tools.isBlack(topValue)) {
  19. topValue = '0'
  20. }
  21. if (tools.isBlack(pName)) {
  22. pName = 'pid'
  23. }
  24. if (tools.isBlack(name)) {
  25. name = 'id'
  26. }
  27. return tools.createTree(list, topValue, pName, name)
  28. },
  29. createTree: (list, pid, pName, name) => {
  30. let tree = []
  31. for (let num = 0; num < list.length; num++) {
  32. let data = list[num]
  33. if (data[pName] === pid) {
  34. data['children'] = tools.createTree(list, data[name], pName, name)
  35. tree.push(data)
  36. }
  37. }
  38. return tree
  39. },
  40. /**
  41. * map 排序对 map 的 key 值进行排序
  42. * @param obj
  43. */
  44. sortMap: (obj) => {
  45. // 1.根据数组中的对象,得到排序后的 key,return key2-key1 表示降序
  46. let newkey = Object.keys(obj).sort((key1, key2) => {
  47. return obj[key2] - obj[key1]
  48. })
  49. // 2.用排序后的key构建新的对象数组
  50. let newObj = {}
  51. // 创建一个新的对象,用于存放排好序的键值对
  52. for (var i = 0; i < newkey.length; i++) {
  53. // 遍历 newkey 数组, 向新创建的对象中按照排好的顺序依次增加键值对
  54. newObj[newkey[i]] = obj[newkey[i]]
  55. }
  56. return newObj //返回排好序的新对象
  57. },
  58. findKey: (data, value) => {
  59. let compare = (a, b) => a === b
  60. return Object.keys(data).find((k) => compare(data[k], value))
  61. },
  62. /** 数组拷贝 */
  63. newObjectArrayWithDeepCopy: (items) => {
  64. var newObjectArray = new Array()
  65. for (var itemIndex = 0; itemIndex < items.length; itemIndex++) {
  66. newObjectArray[itemIndex] = deepCopy(items[itemIndex])
  67. }
  68. return newObjectArray
  69. },
  70. /** 对象拷贝 */
  71. newObjectWithDeepCopy: (object) => {
  72. let newObject = {}
  73. newObject = JSON.parse(JSON.stringify(object))
  74. // for (attribute in object) {
  75. // if (typeof object.attribute === 'object' && object.attribute != null) {
  76. // newObject.attribute = deepCopy(object.attribute)
  77. // } else {
  78. // newObject.attribute = object.attribute
  79. // }
  80. // }
  81. return newObject
  82. },
  83. }
  84. export default tools