你好,我想要一个关于如何使用拆分来分隔一个数组的帮助,该数组具有一个具有其属性的对象,该对象的名称、course1、course2和course3为空。具有文本的课程和内容中带有符号+的课程使用split属性将它们分隔在一个数组中,然后封装在一个称为课程的对象数组中,并将其课程标识符、学分和备注放到每个课程对象中,最后将其作为对象显示为原始数组。
请帮帮我,谢谢。
这里我在做代码,但它对我不起作用
//this is my array
var alumno: [
{
'name' : 'ivan hambi apaza',
'course1' : 'HISTORIA DE LA DANZA+2+16',
'course2' : 'HISTORIA+3+17',
'course3' : '',
}
],
//a step that I was doing but it does not come out
alumnoN(){
var newArr = [...this.alumno]
newArr.map(el => {
return el.course1 = el.course1.split('+')
})
newArr.map(el => {
return el.course2 = el.course2.split('+')
})
newArr.map(el => {
return el.course3 = el.course3.split('+')
})
return newArr
}
console.log(alumnoN())
因此,我想要一个这样的对象:
[
{
'name':'ivan hambi apaza',
'courses':[
{'course':'HISTORIA DE LA DANZA','credit':2,'note':16},
{'course':'HISTORIA','credit':3,'note': 17},
]
}
]发布于 2020-08-22 16:25:20
您可以使用flatMap和reduce以及一个自定义函数来返回课程对象
var alumno = [ { name: "ivan hambi apaza", course1: "HISTORIA DE LA DANZA+2+16", course2: "HISTORIA+3+17", course3: "", } ];
getspliob = (course) =>
/\+/g.test(course) // test if course includes +
? ((ob = course.split("+")), // split and get the array
{ course: ob[0], credit: ob[1] || "0", note: ob[2] || "0" }) // build object
: { course: course, credit: 0, note: 0 }; // else return default object
res = alumno.flatMap(({ name, course1, course2, course3 }) => //map the alumno array
Object.values(
[course1, course2, course3].reduce( // use reduce on courses
(r, o) => (
o != "" // check if course is not empty string
? !r[name] // check if object doesn't exist in accumulator r
? (r[name] = { ...r[name], name: name, courses: [getspliob(o)] }) // then build object
: r[name].courses.push(getspliob(o)) // else push to the already existing courses array
: r,
r // return accumulator
),
{}
)
)
);
console.log(res);
https://stackoverflow.com/questions/63533392
复制相似问题