Quiero asignar valores a un objeto que se parece a:
test_data = { projectTitle: 'Test', source: 'home', destination: 'office', variables: { [ speed: 20, velocity: 30 ], [ speed: 10, velocity: 20 ], } }Este es mi código:
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; }Estoy recibiendo el error:
Cannot read properties of undefined (reading '0')¿Cómo puedo solucionar esto?
Mirando la estructura de la propiedad de las variables , parece que la speed y la velocity también deberían ser propiedades de un objeto. Sin embargo, los pones dentro de una matriz.
Así que recomendaría convertir el objeto de variables en una matriz y envolver los elementos dentro de los objetos.
Por ejemplo:
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); }