1. /**
  2. * Maps fields of files for routine automation.
  3. *
  4. * @param {Array<Object>} files An array of file objects. Each file object should have a 'fields' property,
  5. * which is an array of field names.
  6. * @param {Object} mapping A mapping object where keys are field names from the files, and values are the
  7. * corresponding target field names.
  8. * @returns {Array<Object>} An array of mapped file objects. Returns an empty array if input is invalid.
  9. */
  10. function mapFields(files, mapping) {
  11. if (!Array.isArray(files) || typeof mapping !== 'object' || mapping === null) {
  12. console.error("Invalid input: files must be an array and mapping must be an object.");
  13. return [];
  14. }
  15. const mappedFiles = [];
  16. for (const file of files) {
  17. if (typeof file !== 'object' || file === null || !Array.isArray(file.fields)) {
  18. console.warn("Skipping invalid file:", file); //Log invalid files, but continue processing
  19. continue;
  20. }
  21. const mappedFile = {};
  22. for (const field of file.fields) {
  23. if (mapping.hasOwnProperty(field)) {
  24. mappedFile[mapping[field]] = file[field]; // Map field
  25. } else {
  26. mappedFile[field] = file[field]; // Keep original if no mapping
  27. }
  28. }
  29. mappedFiles.push(mappedFile);
  30. }
  31. return mappedFiles;
  32. }

Add your comment