0

I have an array which contains objects. How to output everything from the object to the markup? I think I stuck in this part of code div_child.innerHTML On output I got this cars[object Object] eleven times.

Should be like this:

img car: 'Audi' model: 'A6' age: 2014 price: 20900

let cars = [];

cars[0] = {
  img: 'assets/img/img-1.webp',
  car: 'Audi',
  model: 'A6',
  age: 2014,
  price: 20900
}
// and 9 another objects of cars


let div = document.createElement('div');
div.className = 'cars-list';
for (let key in cars) {
  let div_child = document.createElement('div');
  div_child.className = 'cars-list__item';
  div_child.innerHTML = `${cars}` + `${cars[key]}`; // As I understood this is the root of problem
  div.append(div_child);
}
document.body.append(div);
  • 2
    You need to access the properties. You can't print an object: `Cars[key].car` – Liam Sep 20 '21 at 10:06
  • 1
    You should also be aware of the [differences between `for..of` and `for...in`](https://stackoverflow.com/a/29286412/542251) – Liam Sep 20 '21 at 10:08

1 Answers1

1

Why is using "for...in" for array iteration a bad idea?

I would use a map:

let cars = [{
  img: 'assets/img/img-1.webp',
  car: 'Audi',
  model: 'A4',
  age: 2014,
  price: 20900
},{
  img: 'assets/img/img-2.webp',
  car: 'Audi',
  model: 'A5',
  age: 2014,
  price: 20900
},{
  img: 'assets/img/img-3.webp',
  car: 'Audi',
  model: 'A6',
  age: 2014,
  price: 20900
},
]
// and 9 another objects of cars


let div = document.createElement('div');
div.className = 'cars-list';
div.innerHTML = cars.map(car => `<div class="cars-list__item">${car.car}: ${car.model}</div>`).join("")
document.body.append(div)
mplungjan
  • 169,008
  • 28
  • 173
  • 236