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)
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,
})
})
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With