I’m dealing with a complex nested object in Redux with this general structure: Job > Tasks > Questions > Options
. Here’s some code I wrote a few years ago to update a question within this object:
case UPDATE_QUESTION:
if (!action.payload?.taskId || action.payload?.taskId === state.job.id) {
return {
...state,
job: {
...state.job,
renderedByQuestions: (state.job.renderedByQuestions ?? []).map((question) => {
if (question.id === action.payload?.questionId) {
return performContingentReduction(question);
} else {
return question;
}
}),
},
isDirty: true,
};
} else {
return {
...state,
job: {
...state.job,
tasks: state.job.tasks.map((task) => {
if (task.id === action.payload?.taskId) {
if (action.payload?.isContingent) {
return {
...task,
renderedByQuestions: (task.renderedByQuestions ?? []).map((question) => {
if (question.id === action.payload?.questionId) {
return performContingentReduction(question);
} else {
return question;
}
}),
};
} else {
return {
...task,
questions: task.questions.map((question) => {
if (action.payload?.isNested && question.children) {
return {
...question,
children: question.children.map((childQuestion) => {
if (childQuestion.children) {
return {
...childQuestion,
children: childQuestion.children.map((grandChildQuestion) => {
return grandChildQuestion.id === action.payload?.questionId
? performReduction(grandChildQuestion)
: grandChildQuestion;
}),
};
} else {
return childQuestion.id === action.payload?.questionId
? performReduction(childQuestion)
: childQuestion;
}
}),
};
} else if (question.id === action.payload?.questionId) {
return performReduction(question);
} else if (
question.conditionalQuestionParentId === action.payload?.questionId &&
question.type !== action.payload?.type
) {
return {
...question,
renderedByOptionIds: null,
renderedByMin: null,
renderedByMax: null,
};
} else {
return question;
}
}),
};
}
} else {
return task;
}
}),
},
isDirty: true,
};
}
While this code works, it’s rather complex and “ugly”. Now that we’re in 2024, I wonder if there any technologies that make it easier to update a given item in an array of nested objects?
Robert