Estoy agregando diferentes objetos a una matriz según ciertas condiciones. Creo que estoy repitiendo el mismo código varias veces. Cualquier sugerencia para escribir los códigos de una mejor manera.
this.users.forEach((item) => {
const student = this.students.find((id) => item.user.id == id);
if(student) {
this.schools.push({
'type':'Student',
'info':[{
'name': item.name,
'id': item.Id,
}],
});
}
const teacher = this.teachers.find((id) => item.user.id == id);
if(teacher) {
this.schools.push({
'type':'Teacher',
'info':[{
'name': item.name,
'id': item.Id,
}],
});
}
const staff = this.staffs.find((id) => item.user.id == id);
if(staff) {
this.schools.push({
'type':'Staff',
'info':[{
'name': item.name,
'id': item.Id,
}],
});
}
});
},
------------------------------------
Puedes crear un objeto tipo de usuario que se asigne primero desde la identificación al tipo y luego buscar el tipo por identificación del usuario más adelante.
let userType = {}
this.students.forEach(id => userType[id] = 'Student')
this.teachers.forEach(id => userType[id] = 'Teacher')
this.staffs.forEach(id => userType[id] = 'Staff')
this.users.forEach((item) => {
this.schools.push({
'type': userType[item.Id],
'info':[{
'name': item.name,
'id': item.Id,
}],
});
})
2
Está lanzandoerror. this.students es una matriz [1,2,3,4], lo mismo para otros tipos.this.students viene como indefinido.
Usuario2410266
28/03/2021 a las 14:56
Lo siento, está funcionando como se esperaba. Gracias por tu ayuda.
Usuario2410266
28/03/2021 a las 15:29
------------------------------------
En su código hay 3 push to array que solo tienen tipos diferentes, insUn poco de este.empuje.de.las.escuelas…. puedes crear un método y pasarle el tipo y el elemento (no puedo ver tus datos aquí, pero cuando usas this.schools eso significa que son datos, por lo que también puedes llamarlos de la misma manera en el método)
this.users.forEach((item) => {
const student = this.students.find((id) => item.user.id == id);
if(student) {
this.pushToArray('Student', item)
}
const teacher = this.teachers.find((id) => item.user.id == id);
if(teacher) {
this.pushToArray('Teacher', item)
}
const staff = this.staffs.find((id) => item.user.id == id);
if(staff) {
this.pushToArray('Staff', item)
}
});
},
pushToArray: function (type, item) {
this.schools.push({
'type': type,
'info':[{
'name': item.name,
'id': item.Id,
}],
});
},