I'm trying to loop through an array of car data and create an array of Car objects using a forEach loop. Then, I want to display each car in the appropriate section of the page depending on whether it is "safetied" or not.
Here’s my Car class:
class Car {
constructor(manufacturer, model, year, vin, safetied) {
this.manufacturer = manufacturer;
this.model = model;
this.year = year;
this.vin = vin;
this.safetied = safetied;
}
get outputString() {
return `${this.manufacturer} ${this.model} ${this.year} with ${this.vin}`;
}
}
My car data is in a separate file, cardata.js, and looks like this:
let carData = [];
carData.push(["Cadillac","DeVille",1993,"1FTEW1CM7CK070304",true]);
// ... and many more entries in this same array format
Here’s the logic I originally used in parta.js:
let cars = [];
carData.forEach(car => {
const newCar = new Car(car.manufacturer, car.model, car.year, car.vin, car.safetied);
cars.push(newCar);
});
But this gave me undefined values or didn't work as expected.
Answer
Your data is stored in an array or arrays:
let carData = [];
carData.push(["Cadillac","DeVille",1993,"1FTEW1CM7CK070304",true]);
But you're looking for named properties on the "inner" arrays:
const newCar = new Car(car.manufacturer, car.model, car.year, car.vin, car.safetied);
An array doesn't have properties like manufacturer
or model
, etc. It's just an array of values. You'd reference those values by their index in the array:
const newCar = new Car(car[0], car[1], car[2], car[3], car[4]);
Keep in mind of course that using arrays to store data like this requires that you ensure the values are always in the correct order. A mixed array of values is technically valid, but doesn't organize values in human-readable properties like one would with an object.
Arrays should be used for lists of otherwise similar values. Objects should be used for grouping attributes which collectively describe something.