Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda