我只想在以下数据中添加两个新变量,即slope
和intersect
。 data.csv文件仅包含列出的列 - Levels
,X
,Y
和Size
。我想在下面的数据中添加上面提到的两个新变量。
数据:
[ { "key": "Level1", "values": [ { "x": 118, "y": 106, "size": 1.113207547 }, { "x": 111, "y": 137, "size": 0.810218978 }, { "x": 144, "y": 195, "size": 0.738461538 }, { "x": 116, "y": 129, "size": 0.899224806 }, { "x": 117, "y": 119, "size": 0.983193277 }, { "x": 145, "y": 122, "size": 1.18852459 } ], "slope": 0.52289599949494, "intercept": 0.2795214697252959 }, { "key": "Level2", "values": [ { "x": 172, "y": 193, "size": 0.89119171 }, { "x": 138, "y": 114, "size": 1.210526316 }, { "x": 106, "y": 189, "size": 0.560846561 }, { "x": 123, "y": 141, "size": 0.872340426 }, { "x": 129, "y": 110, "size": 1.172727273 }, { "x": 162, "y": 198, "size": 0.818181818 } ], "slope": 0.52289599949494, "intercept": 0.2795214697252959 }, { "key": "Level3", "values": [ { "x": 191, "y": 104, "size": 1.836538462 }, { "x": 177, "y": 186, "size": 0.951612903 }, { "x": 106, "y": 140, "size": 0.757142857 }, { "x": 131, "y": 161, "size": 0.813664596 }, { "x": 111, "y": 128, "size": 0.8671875 }, { "x": 149, "y": 122, "size": 1.221311475 }, { "x": 200, "y": 126, "size": 1.587301587 } ], "slope": 0.52289599949494, "intercept": 0.2795214697252959 } ]
尝试使用以下功能:
d3.csv("data.csv", function(data) { data.forEach(function(d) { d.x = +d.x d.y = +d.y d.size = +d.size }) //var type = ['Basic Phone', 'Featured Phone', 'Smart Phone'] var nest = d3.nest() .key(function(d) {return d.type;}) .rollup(function(v) {return v.map(function(d) {delete d.type; return d; d.slope = Math.random(), d.intersent = Math.random()})}) .entries(data); d3.select('body').append('pre') .text(JSON.stringify(nest, null, ' ')); })
答案 0 :(得分:1)
function(d) {delete d.type; return d; d.slope = Math.random(), d.intersent = Math.random()}
相当于
function(d) {delete d.type; return d;}
返回后面的内容无法执行。试试
function(d) {delete d.type; d.slope = Math.random(), d.intersent = Math.random(); return d; }
答案 1 :(得分:0)
获取nest.entries()
的输出后,您可以迭代该数组并添加属性:
nest.forEach(function (d) {
d.slope = Math.random();
d.intercept = Math.random();
})