Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new array then splice a string into each, then forEach before MySQL INSERT

I'm struggling with an array issue. I have a React frontend posting an array to a node API for a MySQL INSERT query. The data from frontend consists of an array with 1 object and 6 elements. One of these elements is an array itself.

[
  {
    subjectID: '2',
    studentList: [ [Object], [Object] ],
    subjectTitle: 'Physics',
    subjectLevel: 'IGCSE Level',
    syllabusCode: '0625',
    subjectGroup: 'Humanities'
  }
]

The studentList array:

[ { studentID: '244' }, { studentID: '245' } ]

What I'm trying to achieve is a new array with objects unique to each studentID, so I can run a forEach over it just before . End result looking something like this:

[
  {
    subjectID: "2",
    studentID: "244",
    subjectTitle: "Physics",
    subjectLevel: "IGCSE Level",
    syllabusCode: "0625",
    subjectGroup: "Humanities",
  },
  {
    subjectID: "2",
    studentID: "245",
    subjectTitle: "Physics",
    subjectLevel: "IGCSE Level",
    syllabusCode: "0625",
    subjectGroup: "Humanities",
  },
];

I'm not sure at which point splice will come into it...

Please let me know if I can supply any other code. I'd appreciate any guidance/assistance! (Been coding for about 2 months now)

like image 648
cameronErasmus Avatar asked Oct 24 '25 16:10

cameronErasmus


1 Answers

Use this code :

let parentArr = [
  {
    subjectID: '2',
    studentList: [ [Object], [Object] ],
    subjectTitle: 'Physics',
    subjectLevel: 'IGCSE Level',
    syllabusCode: '0625',
    subjectGroup: 'Humanities'
  }
]


let newArr = [] ;
parentArr.forEach((parent)=>{
  parent.studentList.forEach((child)=>{
    newArr.push({
    subjectID: parent.subjectID,
    studentID: child.studentID,
    subjectTitle: parent.subjectTitle,
    subjectLevel: parent.subjectLevel,
    syllabusCode: parent.syllabusCode,
    subjectGroup: parent.subjectGroup,
    })
  })
})
like image 110
Moein moeinnia Avatar answered Oct 26 '25 06:10

Moein moeinnia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!