I am trying to add new elements to an object in Javascript but I am getting the following error. Uncaught TypeError: Cannot read property 'diagnosis' of undefined. Below is the code snippet where I perform the following action:
var procedimientos = response.procedimientos;
var camposProcedimientosHC = {};
procedimientos.forEach(function(campos, index){
camposProcedimientosHC[index].diagnostico = campos['codigoDiagnostico'];
camposProcedimientosHC[index].servicio = campos['servicio'];
camposProcedimientosHC[index].codigo = campos['codigo'];
camposProcedimientosHC[index].nombre = campos['nombre'];
camposProcedimientosHC[index].valor = campos['valor'];
camposProcedimientosHC[index].codigoActividad = campos['codigoActividad'];
camposProcedimientosHC[index].fechaServicio = $("#fecha_atencion_historia").val();
camposProcedimientosHC[index].codigoActividadDeta = campos['codigoActividadDeta'];
});
I am receiving from response.procedures an array that would be the following:
What can I be doing wrong?
As the error tells you, you are trying to access the property of an undefined object.
In the code when you initialize it
camposProcedimientosHC
is an empty object, in the foreach you are trying to give value to properties of a propertycamposProcedimientosHC
that does not exist and that is why you get an error.You are trying to treat a type variable
OBJECT
as a typeArray
.Try changing this:
to this: