formatObjKey.ts 961 B

1234567891011121314151617181920212223242526272829303132333435
  1. interface Config {
  2. exclude?: string[];
  3. }
  4. type FormatObjKeyType = 'firstUpperCase' | 'firstLowerCase';
  5. export function formatObjKey(obj: any, type: FormatObjKeyType, options?: Config) {
  6. if (obj === null || typeof obj !== 'object') {
  7. return obj;
  8. }
  9. let o: any;
  10. if (Array.isArray(obj)) {
  11. o = [];
  12. for (let i = 0; i < obj.length; i++) {
  13. o.push(formatObjKey(obj[i], type, options));
  14. }
  15. } else {
  16. o = {};
  17. Object.keys(obj).forEach(key => {
  18. o[handelFormat(key, type, options)] = formatObjKey(obj[key], type, options);
  19. });
  20. }
  21. return o;
  22. }
  23. function handelFormat(key: string, type: FormatObjKeyType, options?: Config) {
  24. if (options && options.exclude && options.exclude.includes(key)) return key;
  25. if (type === 'firstUpperCase') {
  26. key = key.replace(/^./, (_: string) => _.toUpperCase());
  27. } else if (type === 'firstLowerCase') {
  28. key = key.replace(/^./, (_: string) => _.toLowerCase());
  29. }
  30. return key;
  31. }