I have an object called 'task' in my code:
const task = ref<Task>({
name: '',
description: '',
type: undefined,
level: 'tactic',
participants: undefined,
stages: undefined,
});
export interface Task extends CommonEntity {
description?: string;
type?: TaskType;
level?: EntityLevel;
participants?: number;
stages?: TaskTypeStage[];
questions?: TaskQuestion[];
materials?: TaskMaterial[];
indicators?: TaskIndicator[];
duration?: number;
images?: [];
program_id?: number;
roles?: TaskRole[];
tables?: TaskTable[];
competences?: TaskCompetence[];
task_type_id?: number;
}
export interface CommonEntity {
id?: number;
name?: string;
created_at?: string;
updated_at?: string;
errors?: ApiErrors;
delete?: boolean;
isTemporaryIdAdded?: boolean;
}
In a method, I need to modify the task object.
function handleSubmit() {
task.value.materials = removeTemporaryIdFromArray<TaskMaterial>(task.value.materials);
task.value.questions = removeTemporaryIdFromArray<TaskQuestion>(task.value.questions);
task.value.roles = removeTemporaryIdFromArray<TaskRole>(task.value.roles);
task.value.tables = removeTemporaryIdFromArray<TaskTable>(task.value.tables);
}
export function removeTemporaryIdFromArray<T>(
entity: TaskMaterial[] | TaskQuestion[] | TaskRole[] | TaskTable[] | undefined
) {
if (entity) {
return entity
.filter((item) => !item.delete || !item.isTemporaryIdAdded)
.map((item) => Object.assign({}, removeTemporaryId<T>(item)));
}
}
export function removeTemporaryId<T>(item: CommonEntity): T {
const { id, isTemporaryIdAdded, ...rest } = item;
return isTemporaryIdAdded ? (rest as T) : { id, ...(rest as T) };
}
I am looking for a way to optimize the handleSubmit function without repeating the same code for each key. How can I improve this?
I tried using a forEach loop with an array of keys, but the value returned is always 'undefined'. Can you suggest a better approach?
(['materials', 'questions', 'roles', 'tables'] as (keyof typeof task.value)[]).forEach((key) => {
task.value[key] = removeTemporaryIdFromArray<typeof key>(task.value[key] as TaskMaterial[]) as undefined;
});
I'm aware that my current solution is not ideal. Do you have any recommendations on how to improve it?