租房小程序前端代码
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.8 KiB

3 months ago
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.dataFix = void 0;
  4. const isObject_1 = require("./isObject");
  5. const TRUE = ['true', 'TRUE', '1', 1];
  6. const FALSE = ['false', 'FALSE', '0', 0];
  7. function dataFix(o, conf, finalKill) {
  8. if (!isObject_1.isObject(o))
  9. return;
  10. const { remove = [], rename = {}, camel = [], bool = [], lowerFirst = false } = conf;
  11. // 删除不需要的数据
  12. remove.forEach(v => delete o[v]);
  13. // 重命名
  14. Object.entries(rename).forEach(v => {
  15. if (!o[v[0]])
  16. return;
  17. if (o[v[1]])
  18. return;
  19. o[v[1]] = o[v[0]];
  20. delete o[v[0]];
  21. });
  22. // 驼峰化
  23. camel.forEach(v => {
  24. if (!o[v])
  25. return;
  26. const afterKey = v.replace(/^(.)/, $0 => $0.toLowerCase()).replace(/-(\w)/g, (_, $1) => $1.toUpperCase());
  27. if (o[afterKey])
  28. return;
  29. o[afterKey] = o[v];
  30. // todo 暂时兼容以前数据,不做删除
  31. // delete o[v];
  32. });
  33. // 转换值为布尔值
  34. bool.forEach(v => {
  35. o[v] = fixBool(o[v]);
  36. });
  37. // finalKill
  38. if (typeof finalKill === 'function') {
  39. finalKill(o);
  40. }
  41. // 首字母转小写
  42. fixLowerFirst(o, lowerFirst);
  43. return dataFix;
  44. }
  45. exports.dataFix = dataFix;
  46. function fixBool(value) {
  47. if (!value)
  48. return false;
  49. if (TRUE.includes(value))
  50. return true;
  51. return FALSE.includes(value) ? false : value;
  52. }
  53. function fixLowerFirst(o, lowerFirst) {
  54. if (lowerFirst) {
  55. Object.keys(o).forEach(key => {
  56. const lowerK = key.replace(/^\w/, match => match.toLowerCase());
  57. if (typeof o[lowerK] === 'undefined') {
  58. o[lowerK] = o[key];
  59. delete o[key];
  60. }
  61. });
  62. }
  63. }