租房小程序前端代码
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.

78 lines
1.7 KiB

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