Search code examples
javascriptobject

Rename nested object keys with q + counter variable


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?


Solution

  • You can remove the nesting with Object.assign, then remove the ga_questions property.

    const 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"};
    Object.assign(q_obj, ...q_obj.ga_questions.map((o, i) => ({['q' + (i + 1)]: o.ga_checkbox})));
    delete q_obj.ga_questions;
    console.log(q_obj);