Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. /* ------------------------------------------------------------------- */
  2. /**
  3. * Parses data and corrects types: from string to boolean | number
  4. *
  5. * @param data - Data to parse
  6. */
  7. /* ------------------------------------------------------------------- */
  8.  
  9. export const parseTypes = (data: any) => {
  10. let result: any = { };
  11.  
  12. // Parse null
  13. if (data === null)
  14. result = null;
  15.  
  16. // Parse string
  17. else if (typeof data === 'string')
  18. if (data.toLowerCase() === 'true')
  19. result = true;
  20. else if (data.toLowerCase() === 'false')
  21. result = false;
  22. else if (!isNaN(+data))
  23. result = +data;
  24. else
  25. result = data;
  26.  
  27. // Parse array
  28. else if (Array.isArray(data))
  29. result = data.map(item => parseTypes(item));
  30.  
  31. // Parse object
  32. else if (typeof data === 'object')
  33. for (const key of Object.keys(data))
  34. result[key] = parseTypes(data[key]);
  35.  
  36. // Else
  37. else
  38. result = data;
  39.  
  40. return result;
  41. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement