/**
* Replaces values in an array of objects.
*
* @param {Array<Object>} records - The array of objects to modify.
* @param {Object} replacements - An object where keys are record identifiers (e.g., IDs)
* and values are objects containing the new values to set.
* @param {string} idKey - The key in each record object that uniquely identifies it.
* @returns {Array<Object>} - The modified array of objects. Returns a copy to avoid modifying the original.
*/
function replaceRecordValues(records, replacements, idKey) {
if (!Array.isArray(records)) {
return []; // or throw an error, depending on desired behavior
}
if (typeof replacements !== 'object' || replacements === null) {
return [...records]; // Return a copy if replacements is invalid
}
const updatedRecords = records.map(record => {
if (typeof record !== 'object' || record === null) {
return record; // return as is if not a valid object.
}
const recordId = record[idKey];
if (recordId in replacements) {
const replacement = replacements[recordId];
if (typeof replacement === 'object' && replacement !== null) {
return { ...record, ...replacement }; // Merge replacement values
}
}
return record; // Return the original record if no replacement found
});
return updatedRecords;
}
Add your comment