简体   繁体   English

D3 js从包含特定键值的对象获取d3.max

[英]D3 js get a d3.max from an object that contains a specific key value

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. 我有以下数据集,并尝试获取d3.max来指定比例域,但仅想从具有key enabled = true的对象中获得d3.max值。 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; }); })

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: 它接受了多个enabled: "true"对象,请检查第二个演示,我在您的数据数组中放置了另一个对象:

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM