1. /**
  2. * Replaces values in an array of objects.
  3. *
  4. * @param {Array<Object>} records - The array of objects to modify.
  5. * @param {Object} replacements - An object where keys are record identifiers (e.g., IDs)
  6. * and values are objects containing the new values to set.
  7. * @param {string} idKey - The key in each record object that uniquely identifies it.
  8. * @returns {Array<Object>} - The modified array of objects. Returns a copy to avoid modifying the original.
  9. */
  10. function replaceRecordValues(records, replacements, idKey) {
  11. if (!Array.isArray(records)) {
  12. return []; // or throw an error, depending on desired behavior
  13. }
  14. if (typeof replacements !== 'object' || replacements === null) {
  15. return [...records]; // Return a copy if replacements is invalid
  16. }
  17. const updatedRecords = records.map(record => {
  18. if (typeof record !== 'object' || record === null) {
  19. return record; // return as is if not a valid object.
  20. }
  21. const recordId = record[idKey];
  22. if (recordId in replacements) {
  23. const replacement = replacements[recordId];
  24. if (typeof replacement === 'object' && replacement !== null) {
  25. return { ...record, ...replacement }; // Merge replacement values
  26. }
  27. }
  28. return record; // Return the original record if no replacement found
  29. });
  30. return updatedRecords;
  31. }

Add your comment