html - Cómo recorrer objetos de Javascript y mostrarlos en tablas
Mi tercer día de clase y se supone que debemos hacer una vista de coche para usar objetos. Tengo cuatro objetos. Quiero hacer una tabla para cada uno con sus claves a la izquierda y sus valores a la derecha. Cuatro tablas una al lado de la otra. Preferiría recorrer las claves para hacer el y recorrer las claves para el He estado experimentando y fracasando miserablemente. Cualquier ayuda sería muy apreciada. Tengo cuatro divs lado a lado que quiero llenar con tablas. Aquí están mis objetos:
Aquí están mis objetos y valores:
let Accord = new Car("Accord", 22500, "Crystal White", "alloy", "bose", "leather", "tinted");
let CRV= new Car("CR-V", 28400, "Midnight Black", "alloy", "stock", "cloth", "no tint");
let Pilot = new Car("Pilot", 36796, "Modern Gray Metallic", "alloy", "bose", "leather", "tinted");
let Fit = new Car("Fit", 17499, "Raspberry Blue", "steel", "stock", "cloth", "no tint");
//Here is the entire object:
class Car extends Vehicle {
wheels: string;
stereo: string;
seatsMaterial: string;
tint: string;
constructor(model, price, color, wheels, stereo, seatsMaterial, tint) {
super(model, price, color);
this.wheels = wheels;
this.stereo = stereo;
this.seatsMaterial = seatsMaterial;
this.tint = tint;
}
}
Respuesta #1
Básicamente, quieres iterar sobre los elementos en el arreglo y dibujar una nueva fila para cada elemento.
Se puede hacer fácilmente así:
function makeTable ( object ) {
// Check type
if ( typeof object !== 'object' ) return false;
// Start our HTML
var html = "<table><tbody>";
// Loop through members of the object
for ( var key in object ) {
// https://jslinterrors.com/the-body-of-a-for-in-should-be-wrapped-in-an-if-statement
if ( !object.hasOwnProperty(key) ) continue;
// Add our row:
html += "<tr><th>" + key + "</th><td>" + object[key] + "</td></tr>";
}
// Finish the table:
html += "</tbody></table>";
// Return the table
return html;
}
Luego puedes ejecutarlo así:
document.body.innerHTML = makeTable(myCarObject);
document.getElementById('some-id').innerHTML = makeTable(myCarObject);
Algunas notas sobre el código anterior
- Comprobando el tipo - Quieres asegurarte de que el argumento pasado sea realmente un objeto, para que no se comporte de manera inesperada.
- La llamada
.hasOwnProperty- Como se explica aquí, a veces los objetos pueden tener propiedades inesperadas cuando se recorre a través de ellos. Esto se debe a su prototipo y a las propiedades que heredan de él. Una buena manera de asegurarse de que el código se comporte como se espera escontinuarel bucle cuando el objeto no tiene esta propiedad
