I am currently working on a form that allows for the creation of duplicate sections. After submitting the form, it generates one large object. To better organize the data and make it compatible with my API, I am developing a filter function to group the duplicates into arrays.
For example:
// initial object
{
question_10: ""
question_10a: ""
question_11_checkbox: false
question_11_checkbox_copy_0: false
question_11_checkbox_copy_1: true
question_11_text: "110 Monroe St"
question_11_text_copy_0: "186 Aspen Road"
question_12_checkbox: false
question_12_checkbox_copy_0: false
question_12_text: "New York"
question_12_text_copy_0: "South Orange"
...
}
// desired output
{
question_10: ""
question_10a: ""
question_11_checkbox: false
question_11_checkbox_copies: [
{ question_11_checkbox_copy_0: false }
{ question_11_checkbox_copy_1: true }
]
question_11_text: "101 Monroe St"
question_11_text_copies: [
{ question_11_text_copy_0: "186 Aspen Road"}
]
question_12_checkbox: false
question_12_checkbox_copies: [
{ question_12_checkbox_copy_0: false}
]
question_12_text: "New York"
question_12_text_copies: [
{ question_12_text_copy_0: "South Orange"}
]
...
}
My progress so far involves filtering out the copies from the original object and creating arrays for them.
// filter out copy keys
const copiesKey = Object.keys(data).filter(key => key.includes('copy'));
const copy = {};
// create arrays for copies
copiesKey.map(copiedQuestion => {
if (!(`${copiedQuestion.slice(0, copiedQuestion.length - 7)}_copies` in copy)) {
copy[`${copiedQuestion.slice(0, copiedQuestion.length - 7)}_copies`] = [];
}
});
However, I am facing difficulty in matching the objects to their respective arrays and pushing them.
For instance:
question_11_text_copies: [
{ question_11_text_copy_0: "186 Aspen Road" }
]
I have attempted to extract the last three keys of the copy_0 object and match it with the array name using array.filter, but it did not yield the expected results.
Can you provide guidance on how to correctly match the 'copy_n' objects to the corresponding array and push them?