Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3 loop array inside data object

data = [   
{"name":"c1","id":4690 ,"day":[1,3], "start":"8:00", "end":"10:00"},
{"name":"c3","id":5283 ,"day":[3,4], "start":"8:00", "end":"17:00"},
{"name":"c4","id":4862 ,"day":[4], "start":"10:00", "end":"12:30"},
{"name":"c5","id":4862 ,"day":[5], "start":"10:00", "end":"12:30"}]

i'm trying to create a rectangle for each day of each object, the following code without the "for" is working and creating a rectangle for day[0], but not working for all the days!!

function markCourses( data)
{

    var coursesGroup = cont.append("g");


    for ( var x=0; x<data[this].day.length; x++)
    {

        var rects = coursesGroup.selectAll("rect").data(data).enter().append("rect")
        .attr("x",function(d){ return d.x_position;})
        .attr("y", function(d){ return d.y_position;})
        .attr("width", function(d){ return d.duration;})
        .attr("height", vSize-6) // the -6 is used here is used for improvement of the interface
        .style("fill",function(d){return d.color;}) . style("opacity",0.6);   
    }

}
like image 227
M.Tamimi Avatar asked Oct 24 '25 19:10

M.Tamimi


1 Answers

You never ever need to write any loop constructs when using D3.

What you have here is a simple nested structure.

svg.selectAll('g.dataObject')
    .data(data)
    .enter()
    .append('g')
    .attr('foo', function (d) {
        // here d is {"name":"c1","id":4 ... } then {"name":"c2" ... } etc
    })
      // let's create a subselection
      .selectAll('rect')
      .data(function (d) { return d.day; })
      .enter()
      .append('rect')
      .attr(function (d) {
          // here d is 1, then 3 for data object with name c1
      })... etc

You can read about nested selections here: http://bost.ocks.org/mike/nest/

like image 159
Oleg Avatar answered Oct 26 '25 08:10

Oleg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!