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

Time:11-02

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)

CodePudding user response:

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,
    })
  })
})

CodePudding user response:

Yoy can use this code

const arr = [
  {
    subjectID: '2',
    studentList: [ {"name":"xyz","studentID":2},
    {"name":"abc","studentID":3} ],
    subjectTitle: 'Physics',
    subjectLevel: 'IGCSE Level',
    syllabusCode: '0625',
    subjectGroup: 'Humanities'
  }
]
var arr1 = []

for (var parent = 0;parent< arr.length;parent  ){
        for (var children = 0; children< arr[parent].studentList.length; children  ){
        arr1.push(
          {
      subjectID: arr[parent].subjectID,
      studentID: arr[parent].studentList[children].studentID,// Here studentID is assumed as a key of student ID you need to replace it with your key
      subjectTitle: arr[parent].subjectTitle,
      subjectLevel: arr[parent].subjectLevel,
      syllabusCode: arr[parent].syllabusCode,
      subjectGroup: arr[parent].subjectGroup,
      }
    )   
    
}
}
console.log(arr1)
// Now you can insert the arr1 into SQL

  • Related