Home > Software design >  How to output everything from the object to the markup?
How to output everything from the object to the markup?

Time:09-22

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);

CodePudding user response:

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)

  • Related