apopa apopa - 4 months ago 14
Javascript Question

JSX generate divs and push to array

I have a structure of the form:

var circle = {
'one': {items: []},
'two': {items: []},
'three': {items: []},
'four': {items: []}
};


Each
items
array should hold 10 unique divs, like this:

circle.one.items
array should hold:

<div className="item item-1">1</div>

...
<div className="item item-10">10</div>


...

circle.four.items
array should hold:

<div className="item item-31">31</div>

...
<div className="item item-40">40</div>


And I'm using the structure like this:

<div className="circle-one">
{circle.one.items}
</div>


How do I populate the
items
arrays with those divs?

Answer

You could use an array and loop the array for the items.

var circle = { 'one': { items: [] }, 'two': { items: [] }, 'three': { items: [] }, 'four': { items: [] } };

['one', 'two', 'three', 'four'].forEach(function (k, i) {
    for (var j = 1; j <= 10; j++) {
        circle[k].items.push('<div className="item item-' + (i * 10 + j) + '">' + (i * 10 + j) + '</div>');
    }
});

console.log(circle);