数据对象内部的D3循环数组 [英] D3 loop array inside data object

查看:123
本文介绍了数据对象内部的D3循环数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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"}]

我正在尝试为每个对象的每一天创建一个矩形, 以下没有"for"的代码正在工作,并为day [0]创建了一个矩形,但并非所有天都工作!

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

}

推荐答案

使用D3时,您永远不需要编写任何循环结构.

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

您可以在此处了解有关嵌套选择的信息: http://bost.ocks.org/mike/nest/

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

这篇关于数据对象内部的D3循环数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆