Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

146
Vistas
Javascript: Cannot read properties of undefined (reading '0') which assigning value to object

I want to assign values to an object which looks like:

test_data = {
 projectTitle: 'Test',
 source: 'home',
 destination: 'office',
 variables: {
    [
      speed: 20,
      velocity: 30
    ],
    [
      speed: 10,
      velocity: 20
    ],
 }
}

This is my code:

test_data: any = {}

test_data.projectTitle = (document.getElementById("project_title") as HTMLInputElement).value;
test_data.source = (document.getElementById("source") as HTMLInputElement).value;
test_data.destination = (document.getElementById("destination") as HTMLInputElement).value;

for (let i=0;i<2;i++) {
   test_data.variables[i].speed = (document.getElementById("speed_"+i) as HTMLInputElement).value;
   test_data.variables[i].velocity = (document.getElementById("velocity_"+i) as HTMLInputElement).value;
}

I am getting the error:

Cannot read properties of undefined (reading '0')

How do i fix this?

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

Looking at the structure of the variables property, it seems that speed and velocity should be properties of an object too. You put those inside an array though.

So I'd recommend turning the variables object into an array and wrap the elements inside objects.

For example:

let test_data = {
 projectTitle: 'Test',
 source: 'home',
 destination: 'office',
 variables: [
    {
      speed: 20,
      velocity: 30
    },
    {
      speed: 10,
      velocity: 20
    },
 ]
}

for (let i=0;i<2;i++) {
  console.log(test_data.variables[i].speed);
   console.log(test_data.variables[i].velocity);
}

about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda