I have the following object, which I am iterating over to fill it into a table. It works correctly for me, the detail is that when I add more objects, it paints the objects in this order:
object 1, object 2, object 3, object 1, object 2, object 3, object 1, object 2, object 3... like this 5 times.
And the result I would like is to paint myself like this:
object1, object2, object3, object1, object2.
I attach my code:
let obj = {
campo: [
{
id: '1',
nombre: 'Teclados',
descripcion: 'Producto para computadoras',
categoria: 'Tecnología',
},
{
id: '2',
nombre: 'Cubiertos',
descripcion: 'Materiales de cocina y hogar',
categoria: 'Cocina',
},
{
id: '3',
nombre: 'Macetas',
descripcion: 'Objetos decorativos de casa',
categoria: 'Decoraciones',
},
],
};
function rellenarTabla(obj) {
let tbody = document.getElementById('tablaArray');
for (let i = 1; i <= 5; i++) {
obj.campo.forEach(c => {
let filaNueva = '<tr>' +
'<td><strong>' + c.id + '</strong></td>' +
'<td>' + c.nombre + '</td>' +
'<td>' + c.descripcion + '</td>' +
'<td>' + c.categoria + '</td>' +
'</tr>';
tbody.innerHTML += filaNueva;
});
}
}
rellenarTabla(obj);
<section class="bg-white">
<div class="container pb-4 pt-0">
<h4>Tabla con arreglo</h4>
<div class="row py-4">
<div class="col-lg-12 col-md-12 mb-lg-0">
<table class="table table-white table-hover table-striped table-bordered">
<thead class="tituloCrear2b">
<tr>
<th id="codigo">Código</th>
<th id="nombre">Nombre</th>
<th id="descripcion">Descripción</th>
<th id="categoria">Categoría</th>
</tr>
</thead>
<tbody id="tablaArray"></tbody>
</table>
</div>
</div>
</div>
</section>