Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!