I have an object that has a nested object within it. When I try to insert this data into a database table, I get an error because it’s looking for a column called ga_questions
.
What I need is to break down ga_questions
to be a key/value like "q1": "false"
so I can insert each checkbox value into the DB. The key needs to increment for each checkbox so the next entry would like "q2": "true"
, and so on and so forth.
I’m having trouble getting the incrementing to work.
q_obj = {
"GAInsSig": "Skylar",
"GAnotes": "",
"GAInsSig2": "",
"ga_questions": [{
"ga_checkbox": false
}, {
"ga_checkbox": false
}, {
"ga_checkbox": false
}, {
"ga_checkbox": false
}, {
"ga_checkbox": false
}, {
"ga_checkbox": false
}, {
"ga_checkbox": false
}, {
"ga_checkbox": false
}, {
"ga_checkbox": false
}, {
"ga_checkbox": false
}, {
"ga_checkbox": false
}, {
"ga_checkbox": false
}, {
"ga_checkbox": true
}, {
"ga_checkbox": true
}, {
"ga_checkbox": true
}],
"badge_num": "12345",
"work_order": "123",
"unit_num": "123",
"job_num": "GET",
"date_completed": "2024-01-17"
}
Below is the code I have tried so far.
let i = 1;
q_obj.map((el) => {
let question = "q";
question.concat(i);
el.question = el.ga_checkbox;
i++;
delete el.ga_checkbox;
});
This will rename my keys to just question. Is there another way to do this so that I can have the keys of this nested object start with 'q'
+ the value of i
?
2
Answers
You can remove the nesting with
Object.assign
, then remove thega_questions
property.Bro, if my English is bad I’m sorry, but I think I understand your question. You can use a combination of UYM array mapping and dynamic object keys, for example: