问题
I just wanted to add two new variables in the below data i.e., slope and intersect. data.csv file contains only the listed columns - Levels, X, Y and Size. I wanted to add two new variables mentioned above in the below data.
Data :
[
{
"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
}
]
Tried with the below function :
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, ' '));
})
回答1:
After getting the output from the nest.entries(), you can iterate that array and add your properties:
nest.forEach(function (d) {
d.slope = Math.random();
d.intercept = Math.random();
})
回答2:
function(d) {delete d.type; return d; d.slope = Math.random(), d.intersent = Math.random()}
is equivalent to
function(d) {delete d.type; return d;}
What follows return doesn't get to be executed. Try
function(d) {delete d.type; d.slope = Math.random(), d.intersent = Math.random(); return d; }
来源:https://stackoverflow.com/questions/19833322/d3-nest-adding-extra-variables