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?
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);
}