d3.js:访问数据嵌套向下2级 [英] d3.js: Access data nested 2 level down
问题描述
数据结构:
var data = [
{name: "male",
values: [
{ count: 12345,
date: Date 2015-xxx,
name: "male" },
{...}
]
},
{name: "female",
values: [
{ count: 6789,
date: Date 2015-xxx,
name: "female" },
{...}
]
}
]
我要访问的值是data [a] .values [b] .count
The values that I want to access are data[a].values[b].count
这些值用于绘制我的图的圆
The values are used to draw circles for my plot
圆图的代码:
focus.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
.attr("cx", function(d,i) { return x(d.values[i].date); })
.attr("cy", function(d,i) { return y(d.values[i].count); })
.attr("r", 4)
.style("fill", function(d,i) { return color(d.values[i].name); })
问题在于i = 1
由于其在对象中的位置.
The problem is that i = 1
because of its position in the object.
我想做的是遍历values
下的所有objects
.我怎样才能做到这一点?
What I want to do is to loop through all the objects
under values
. How can I do that?
我希望学习如何在不更改数据的情况下做到这一点,以提高我的技能.
I wish to learn how to do it without altering the data, to improve on my skills.
谢谢.
推荐答案
最简单的方法是使用underscore.js之类的库来编辑数据数组.
The easiest way is to use a lib like underscore.js to edit your data array.
来自下划线文档:
展平 _.flatten(数组,[浅]) 展平嵌套数组(嵌套可以达到任何深度).如果通过浅层,则>该数组将仅展平一个级别.
flatten _.flatten(array, [shallow]) Flattens a nested array (the nesting can be to any depth). If you pass shallow, >the array will only be flattened a single level.
_.flatten([1, [2], [3, [[4]]]]);
-> [1, 2, 3, 4];
_.flatten([1, [2], [3, [[4]]]], true);
-> [1, 2, 3, [[4]]];
地图 _.map(列表,iteratee,[上下文])别名:收集 通过>转换函数(iteratee)映射列表中的每个值,从而产生一个新的值数组. iteratee传递了三个参数:> value,然后是迭代的索引(或键),最后是对> entire列表的引用.
map _.map(list, iteratee, [context]) Alias: collect Produces a new array of values by mapping each value in list through a >transformation function (iteratee). The iteratee is passed three arguments: the >value, then the index (or key) of the iteration, and finally a reference to the >entire list.
_.map([1, 2, 3], function(num){ return num * 3; });
=> [3, 6, 9]
_.map({one: 1, two: 2, three: 3}, function(num, key){ return num * 3; });
=> [3, 6, 9]
_.map([[1, 2], [3, 4]], _.first);
=> [1, 3]
在您的代码中,您可以执行以下操作:
In your code you can do something like that:
var flatData = _.flatten(_.map(data, (d)=>d.values));
focus.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
.attr("cx", function(d,i) { return x(d.date); })
.attr("cy", function(d,i) { return y(d.count); })
.attr("r", 4)
.style("fill", function(d,i) { return color(d.name); })
这篇关于d3.js:访问数据嵌套向下2级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!