Push items in an array in Javascript?

I’m working on school-app. person enter students marks from frontend and I’ve to store it in my backend. I know my data-structure is quite bad. but this is only way I can comfortly use and fit it in my front end application/website.

codeSandbox link

Full Code:

//This data is already set need to push information in this array.
let student = [{
  "detail": {
      "name": "Mark",
      "surname":"widen"
  },
}];


//Here's data recieving from frontend like this:

let query = {
      "marks,mark": "500,200"
  }

//formatting the query in json.

  const keys = Object.keys(query)[0].split(",")
  const values = Object.values(query)[0].split(",")

  const newObj = {}

  for (let i = 0; i < keys.length; i++) {
      newObj[keys[i]] = values[i]
    }

//  I've to push it along with "academic-year". so,

     for (let a = 0; a < newObj.length; a++) {
       const year = a + "st-Year"
       console.log(year) // Expected Output: 1st-Year and 2nd-Year
    }

// How to run this both for-loop synchronously way ?? AND

//pushing with "ObtainedMarks" and "year" (Error over here)
  student.push({
      ObtainedMarks: {
          year : [  
              { physics: newObj }
          ],

          year : [
              { physics: newObj }
          ]
      }
  })

console.log(student) //Here's I want expected Output

Expected Output:

let student = [{
  "detail": {
      "name": "Mark",
      "surname":"widen"
  },

  ObtainedMarks: {
    "1st-Year": [
              { physics: { "marks": "500" } } //Physics subject is default.
          ],

          "2nd-Year": [
              { physics: { "mark": "200" } } //Physics subject is default.
         ]
   }
}];

I want to push returned data in student array. with 1st-Year and 2nd-Year's for-loop.

Answer

You can do the conversion in your for-loop

let student = [{
  "detail": {
    "name": "Mark",
    "surname": "widen"
  },
}];

let query = {
  "marks,mark": "500,200"
}

const keys = Object.keys(query)[0].split(",");
const values = Object.values(query)[0].split(",");

const marks = {}

for (let i = 0; i < keys.length; i++) {
  marks[i === 0 ? `${i+1}st-year` : `${i+1}nd-year`] = [{
    physics: {
      [keys[i]]: values[i]
    }
  }];
}


student.push({
  obtainedMarks: marks
});

console.log(student);

Alternative way: map through the keys and create an object from entries after manipulating the data.

let student = [{
  "detail": {
    "name": "Mark",
    "surname": "widen"
  },
}];

let query = {
  "marks,mark": "500,200"
}

const keys = Object.keys(query)[0].split(",");
const values = Object.values(query)[0].split(",");

const marks = Object.fromEntries(keys.map((k, i) => {
  return [
    i === 0 ? `${i+1}st-year`: `${i+1}nd-year`, 
    [{ physics: { [k]: values[i] }}]
  ];
}));

student.push({
  obtainedMarks: marks
});

console.log(student);