NodeJS 创建新数组,然后将字符串拼接到每个数组中,然后在MySQL INSERT之前创建forEach

wbgh16ku  于 2022-11-03  发布在  Node.js
关注(0)|答案(2)|浏览(177)

我遇到了一个数组问题。我有一个React前端向一个节点API发布一个数组,用于MySQL INSERT查询。来自前端的数据由一个包含1个对象和6个元素的数组组成。其中一个元素是数组本身。

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

studentList数组:

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

我尝试实现的是一个新的数组,其中的对象对于每个studentID都是唯一的,这样我就可以在之前对它运行一个forEach。最终结果如下所示:

[
  {
    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",
  },
];

我不知道在哪一点上拼接会进入它...
请让我知道,如果我可以提供任何其他代码。我会感激任何指导/协助!(一直编码约2个月了)

wf82jlnq

wf82jlnq1#

使用此代码:

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

xeufq47z2#

Yoy可以使用此代码

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

相关问题