I'm looking for help with this. I have this function to get all the employees of my app.
function listar_empleados() {
funcion = "listar_empleados";
$.post("/bureau-veritas/Controllers/EmpleadosController.php", { funcion }, (response) => {
const employees = JSON.parse(response);
/* Group employees by department */
let employeeGroups = {};
employees.forEach((employee) => {
if (!employeeGroups[employee.departamento]) {
employeeGroups[employee.departamento] = [];
}
employeeGroups[employee.departamento].push(employee);
});
console.log(employeeGroups);
/* Generate HTML template */
let template = '';
for (let departamento in employeeGroups) {
template += `<optgroup label="${departamento}">`;
employeeGroups[departamento].sort((a, b) => (a.nombre > b.nombre) ? 1 : -1)
.forEach((employee) => {
template += `<option value="${employee.rfc}" data-subtext="${employee.rol}">${employee.nombre} ${employee.apellidos}</option>`;
});
template += '</optgroup>';
}
$('#crearcontrato_encargado_suplente').html(template).selectpicker('refresh');
});
}
When the request is done, I get an object like this where all employees are grouped by their department. The keys are:
- rfc -> it's the primary key of each employee
- nombre -> name
- apellidos -> last names
- departamento -> the department where the employee has been assign
- role -> the role or title of the employee in their departments
- estado -> boolean for knowing if an employee is active or not
{
"Contabilidad": [
{
"rfc": "CENAWELIO2023",
"nombre": "Jonathan",
"apellidos": "Martinez",
"departamento": "Contabilidad",
"rol": "Jefe de departamento",
"estado": "1"
}
],
"Industria": [
{
"rfc": "FEESHAMOR2023",
"nombre": "Francisco",
"apellidos": "Cerino",
"departamento": "Industria",
"rol": "Representante Técnico",
"estado": "1"
},
{
"rfc": "JORGE-ARPAIZ",
"nombre": "Jorge",
"apellidos": "Arpaiz Herrera",
"departamento": "Industria",
"rol": "Representante Técnico",
"estado": "1"
},
{
"rfc": "MIGUELNARANJO",
"nombre": "Miguel Ángel",
"apellidos": "Naranjo",
"departamento": "Industria",
"rol": "Jefe de departamento",
"estado": "1"
},
{
"rfc": "QUMO0009066E3",
"nombre": "Oscar",
"apellidos": "Quevedo",
"departamento": "Industria",
"rol": "Auxiliar de departamento",
"estado": "1"
}
]
}
As you see, the object is fine, but the trouble comes when it's time to print the template.
I don't know why the template is printing like this.
I've done console.log(template) already to be sure of it's generating properly, and it does, but the template I get it's the same, and only one, employee on different departaments. In the pic it seems the departments are been showing as well.
What I am expecting to get it's a template like this, but the header of groups showing the department title with their employees with each employee role.
Hope anyone can help me. ^^