transformData.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import pinyin from 'pinyin';
  2. interface Region {
  3. title: string;
  4. list: any[];
  5. }
  6. export const transformData = (regionData: any[]) => {
  7. if (!Array.isArray(regionData)) throw new TypeError('params muse be array.');
  8. if (!regionData.length) return [];
  9. const newData: Region[] = [];
  10. regionData = regionData.map((item: any) => {
  11. if (!item.name) return new Error('the data must includes `name` props');
  12. let code = pinyin(item.name, {
  13. style: pinyin.STYLE_NORMAL
  14. });
  15. return {
  16. ...item,
  17. firstCode: code[0][0].charAt(0).toUpperCase()
  18. };
  19. });
  20. regionData = regionData.sort((a: any, b: any) => {
  21. return a.firstCode.localeCompare(b.firstCode);
  22. });
  23. regionData.forEach((item: any) => {
  24. const index = newData.findIndex(
  25. (value: any) => value.title === item.firstCode
  26. );
  27. if (index <= -1) {
  28. newData.push({
  29. title: item.firstCode,
  30. list: [].concat(item)
  31. });
  32. } else {
  33. newData[index] = {
  34. title: item.firstCode,
  35. list: newData[index].list.concat(item)
  36. };
  37. }
  38. });
  39. return newData;
  40. };