how can i loop through an object and out put divs with classes ?
hello
i trying to create a bar graph
i have this object for the bars, tears and totTears.
- var graphObjects = [
{
id: 1,
tears: 2,
seletedTears: 1,
},
{
id: 2,
tears: 2,
seletedTears: 2,
},
{
id: 3,
tears: 3,
seletedTears: 2,
},
{
id: 4,
tears: 4,
seletedTears: 4,
}
];
I would like the out put to be something like this
- <div class="graphContainer">
<div id="bar1" class="bar">
<div class="tear1 selected"></div>
- <div class="tear2"></div>
</div>
- <div id="bar2" class="bar">
<div class="tear1 selected"></div>
- <div class="tear2 selected"></div>
</div>
- <div id="bar3" class="bar">
<div class="tear1 selected"></div>
- <div class="tear2 selected"></div>
- <div class="tear3"></div>
</div>
- <div id="bar4" class="bar">
<div class="tear1 selected"></div>
- <div class="tear2 selected"></div>
- <div class="tear3 selected"></div>
- <div class="tear4 selected"></div>
</div>
- </div>
i have set up this loop to create the number of bars in the graph depending on the number of objects
- //number of bars in graph
$('.graphContainer').html("");
var numBars = $(graphObjects).length;
// create bars for graph
for (i=1; i<=numBars; i++)
{
$(".graphContainer").append('<div id="bar'+i+'"class="bar">bar</div>');
}
that gives me
- <div class="graphContainer">
<div id="bar1" class="bar">bar</div>
- <div id="bar2" class="bar">bar</div>
- <div id="bar3" class="bar">bar</div>
- <div id="bar4" class="bar">bar</div>
- </div>
if i do an each on the object i can console.log them like this
- $.each(graphObjects, function(name, value){
id = $(this.id);
tears = $(this.tears);
selectedTears = $(this.selectedTears);
-
- console.log(id);
console.log(tears);
console.log(selectedTears);
});
but now i am stuck :( i can not work out how to add the inner tear divs ?
so for each bar i needs to have the correct number of tears. i.e bar 1 has 2 tears like in the object.
then in bar bar only 1 tear has a selected class.
please help.
Many thanks
Kind regards
Ricky