JSX generates divs and clicks on an array

I have a view structure:

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

Each array itemsmust contain 10 unique divs, for example:

circle.one.items the array should contain:

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

...

circle.four.items the array should contain:

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

And I use the structure as follows:

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

How to fill arrays with itemsthese divs?

+4
source share
4 answers

You can use an array and loop the array for elements.

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);
Run code
+3
source

If you have a starting object, then a simple nested loop will work very well:

var keys = ["one","two","three","four"];
for (var i = 0; i < keys.length; i++) {
    for (var j = 0; j < 10; j++) {    // Note: you might want to avoid the magic number here
        circle[keys[i]].items.push(createDiv(i * 10 + j + 1));
    }
}

where createDivis a function that takes a number for yours item-xxand returns the actual div you want.

, , . , Object.keys, .

+1

Not sure if you want these divs to be strings. In any case, you can update the function populateItemsbelow to return what you want.

var mapping = { one:1, two:2, three:3, four: 4};

function populateItems(n) {
  var output = [];
  for (var i = 1; i <= 10; i++) {
    var curr = i+(n-1)*10;
    output.push('<div className="item item-'+curr+'">+'curr+'</div>');
  }
  return output;
}

for (p in circle) {
  circle[p].items = populateItems(mapping[p]);
}
0
source

if you use underscore / lodash you can do this:

_.each(circle, (obj) => {
    obj.items = _.map(_.range(10), (n) => {
        return <div className={'item item'+n}>n</div>
    });
});

my variable name is pretty terrible.

0
source

All Articles