【问题标题】:Handling nested data arrays处理嵌套数据数组
【发布时间】:2014-01-08 21:52:00
【问题描述】:

我被困住了... 我想使用嵌套数组中字段的数据。我是新手,所以我错过了一些部分:-( 如果在调试d[0].children[1].birthdate 中写入,我会得到正确的值。当我尝试绘制我的日期时,我只能从我的“父母”数据中获得第一个孩子。

   //Part of my code:

    circle.append("circle") 
    .style("fill", "purple")
    .attr("r", 5)
    //This get me each parent first child but I need all the children e.g Adam, Eve, Julia....
    .attr("cx", function(d,i,j) { return x(new Date(d.parent[j].birthdate));}) 

我的数据:

"parent":[
     "name": "Mum",
       "children": [
            {
                "name": "Adam",
                "birthdate": "2013-01-05"
            },
            {
                "name": "Eve",
                "birthdate": "2013-02-05"
            },
            {
                "name": "Julia",
                "birthdate": "2013-03-05"
            }
        ]
    },        
    {
        "name": "Dad",
        "children": [
            {
                "name": "Romeo",
                "birthdate": "2013-04-05"
            },
            {
                "name": "Maria",
                "birthdate": "2013-03-15"
            }
        ]
    },
    "name": "StepMom",
       "children": [
            {
                "name": "A",
                "birthdate": "2013-01-05"
            },
            {
                "name": "B",
                "birthdate": "2013-02-05"
            },
            {
                "name": "C",
                "birthdate": "2013-03-05"
            }
        ]
    }
    ]           

【问题讨论】:

    标签: javascript arrays d3.js nested


    【解决方案1】:

    不清楚您要做什么,但在您的代码中您没有.children。也就是说,而不是

    .attr("cx", function(d,i,j) { return x(new Date(d.parent[j].birthdate));})
    

    你可能想要

    .attr("cx", function(d,i,j) { return x(new Date(d.children[j].birthdate));})
    

    另一方面,您应该正确解析日期,而不是依赖浏览器来解析:

    .attr("cx", function(d,i,j) { return x(d3.format("%Y-%m-%d").parse(d.children[j].birthdate));})
    

    【讨论】:

    • 嗨 Lars 感谢您的快速回答。我早些时候尝试过带孩子的那个,但这对我没有帮助:-(。我仍然只是得到每个父母的第一个孩子。我知道这不是正确的语法,但如果我可以写类似:d.parent[i] .child[j].birthdate 会给我正确的答案。我已将我的数据附加到我从 json 文件 .data(tasks); 中读取的全部数据中
    • 嗨,我设法解决了这个问题: var circleGroups = svg.selectAll('g.main') .data(parent) .enter() .append('g') .classed( '主要',真); circleGroups.selectAll('g.sub') .data(function(d) { return d.birthdate; }) .enter() .append('circle') .classed('sub', true) 这是我工作的一个问题与之前。我现在和父母一起做一个盒子,在那个盒子里我画出孩子们。感谢您花时间帮助我。玛丽亚
    猜你喜欢
    • 2019-12-27
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 2013-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多