数组常用用法--map,filter,reduce
map:
const studentsWithGrade = students.map(student => { return { ...student, grade:student.score >= 60? '通过':'不合格' } })
用...student:
- 创建新对象,这样后续的操作就不会影响原来的students
- 可以出现BUG的地方减少一个是一个
- 但如果数组较大会性能消耗
// 联合 const studentsWithGroupInfo = students.map(student => { const group = groups.find(g => g.id === student.group_id) return{ ...student, groupName:group.name } }) // 在第一张表students的每个student在通过id第二张表groups里找对应的group
fIlter:
// 通过的学员 const passedStudents = students.filter(x => x.score > 60) //组1的学员 const ground1Students = students.filter(x => x.group_id === 1)
reduce:
// 分组 const studentsInGroups = students.reduce((groups,student) => { groups[student.group_id] = [...(groups[students.group_id] || []),student] return groups },{}) // 这指的是一开始给groups定义一个空对象,通过判断这个组是否有group._id的学生,没有就创建一个空数组。然后再解构出来和student一起
结果: