I'm not sure if I have a misconception on how to organise my array or on how to access it.
Proposition is simple: Have an array of car makes and models and access them for display.
const carBrands = [
{
Audi: {
models: ["A1", "A2", "A3", "A4"],
unitsAvailable: 378,
}
},
{
BMW: {
models: ["M1", "M2", "M3", "M4"],
unitsAvailable: 413,
},
},
{
Honda: {
models: ["H1", "H2", "H3", "H4"],
unitsAvailable: 226,
},
}
];
I can access each model as such:
carBrands.forEach((object, i) => {
console.log(object, i)
});
This a returns my objects and index fine:
Audi 0 BMW 1 Honda 2
What I can't figure out is how to return:
Make: Audi Models: A1, A2, A3, A4 Units available: 378
... for each of the 3 cars.
I know I have to loop over the array and return for each loop the object key/value pairs. But I'm having trouble with the correct syntax. Here's what I'm trying to figure out how to formulate:
let modelsToDisplay = [];
carBrands.forEach((object, i) => {
modelsToDisplay.push(<li key={i}>Make/Model/Units of each object</li>);
});
Thanks for helping out :)
Object.values()andObject.keys()?carBrandsbe an object instead OR structure your objects where the make is a value, instead of a key. Such as:carBrands = [ { make: ‘Audi’, models: [‘A4’, ‘A5’] }, { make: ‘BMW’, models: [‘M3’, ‘M4’] } ].Object.getOwnPropertyNames(like this:Object.getOwnPropertyNames(carBrands)) is my good friend.