apopa
apopa

Reputation: 170

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?

Upvotes: 4

Views: 466

Answers (4)

Nicola Pedretti
Nicola Pedretti

Reputation: 5166

if you use underscore/lodash you could do this:

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

my variable naming is pretty terrible btw!

Upvotes: 0

apieceofbart
apieceofbart

Reputation: 2197

Not sure if you wanted those divs as strings. Anyway you can update populateItems function below 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]);
}

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386644

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

Upvotes: 3

Matt Burland
Matt Burland

Reputation: 45145

Given you have you starting object, then a simple nested loop would work just fine:

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 createDiv is a function that takes the number for your item-xx and returns the actual div you want.

The one thing to note here is that I have defined an array with the keys to your object in the order that I want them. You should not rely on, for example Object.keys returning the keys in any defined order.

Upvotes: 1

Related Questions