问题
I have the following dataset and am trying to get the d3.max to specify a domain for a scale, but want the d3.max value only from objects that have the key enabled=true. How can this be achieved?
[{
"key": "name1",
"enabled": "true",
"values": [{
"date": "2016-09-13T02:11:44Z",
"value": "100",
}, {
"date": "2016-09-13T02:11:44Z",
"value": "200",
}]
}, {
"key": "name2",
"enabled": "false",
"values": [{
"date": "2016-09-13T02:11:44Z",
"value": "400",
}, {
"date": "2016-09-13T02:11:44Z",
"value": "500",
}]
}]
I think I am supposed to use a key somehow, but haven't been able to do it. Can someone point me to the right direction? This is what I have so far...
d3.max(dataset, function(c) { return d3.max(c.values, function(d) { return d.value; }); })
回答1:
If you want it in one line:
var max = d3.max(data.filter(d => d.enabled === "true"), e => d3.max(e.values, f => f.value));
Or, without the arrow functions:
var max = d3.max(data.filter(function(d) {
return d.enabled === "true";
}), function(e) {
return d3.max(e.values, function(f) {
return f.value;
});
});
Here is a demo:
var data = [{
"key": "name1",
"enabled": "true",
"values": [{
"date": "2016-09-13T02:11:44Z",
"value": "100",
}, {
"date": "2016-09-13T02:11:44Z",
"value": "200",
}]
}, {
"key": "name2",
"enabled": "false",
"values": [{
"date": "2016-09-13T02:11:44Z",
"value": "400",
}, {
"date": "2016-09-13T02:11:44Z",
"value": "500",
}]
}];
var max = d3.max(data.filter(d => d.enabled === "true"), e => d3.max(e.values, f => f.value));
console.log(max);
<script src="https://d3js.org/d3.v4.min.js"></script>
It accepts more than one object with enabled: "true"
, check this second demo, I put another object in your data array:
var data = [{
"key": "name1",
"enabled": "true",
"values": [{
"date": "2016-09-13T02:11:44Z",
"value": "100",
}, {
"date": "2016-09-13T02:11:44Z",
"value": "200",
}]
}, {
"key": "name2",
"enabled": "false",
"values": [{
"date": "2016-09-13T02:11:44Z",
"value": "400",
}, {
"date": "2016-09-13T02:11:44Z",
"value": "500",
}]
},{
"key": "name1",
"enabled": "true",
"values": [{
"date": "2016-09-13T02:11:44Z",
"value": "800",
}, {
"date": "2016-09-13T02:11:44Z",
"value": "200",
}]
}];
var max = d3.max(data.filter(d => d.enabled === "true"), e => d3.max(e.values, f => f.value));
console.log(max);
<script src="https://d3js.org/d3.v4.min.js"></script>
来源:https://stackoverflow.com/questions/42930052/d3-js-get-a-d3-max-from-an-object-that-contains-a-specific-key-value