Insert.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { generateId } from './Common';
  2. /**
  3. * function to convert uploaded csv to MilvusGrid component accepted data type
  4. * @param data uploaded csv data, e.g. [['name1', 12], ['name2', 14]]
  5. * @returns key value pair object array, use index as key, e.g. [{0: 'name1', 1: 12}, {0: 'name2', 1: 14}]
  6. */
  7. export const transferCsvArrayToTableData = (data: any[][]) => {
  8. return data.reduce(
  9. (result, arr) => [...result, { ...arr, id: generateId() }],
  10. []
  11. );
  12. };
  13. /**
  14. * function to replace object key
  15. * @param obj e.g. {0: 'name1', 1: 12, 2: 'red'}
  16. * @param newKeys e.g. ['name', 'age', 'color']
  17. * @returns e.g. {name: 'name1', age: 12, color: 'red'}
  18. */
  19. const replaceKeysByIndex = (obj: any, newKeys: string[]) => {
  20. const keyValues = Object.keys(obj).map(key => {
  21. const newKey = newKeys[Number(key)] || key;
  22. return { [newKey]: parseValue(obj[key]) };
  23. });
  24. return Object.assign({}, ...keyValues);
  25. };
  26. export const parseValue = (value: string) => {
  27. try {
  28. return JSON.parse(value);
  29. } catch (err) {
  30. return value;
  31. }
  32. };
  33. /**
  34. *
  35. * @param heads table heads, e.g. ['field1', 'field2', 'field3']
  36. * @param data table data, e.g. [[23, [2,3,34,4,5,56], [1,1,1,1,1,1,1,1,1,1,1]]]
  37. * @returns key value pair object array, with user selected heads or csv heads
  38. */
  39. export const combineHeadsAndData = (heads: string[], data: any[]) => {
  40. // use index as key, flatten two-dimensional array
  41. // filter useless row
  42. const flatTableData = data
  43. .filter(d => d.some((item: string) => item !== ''))
  44. .reduce((result, arr) => [...result, { ...arr }], []);
  45. // replace flatTableData key with real head rely on index
  46. return flatTableData.map((d: any) => replaceKeysByIndex(d, heads));
  47. };