D3.js-如何获取对象中指定键的最大值 [英] D3.js-How can I get the maximum value of a specified key in an object

查看:615
本文介绍了D3.js-如何获取对象中指定键的最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个数组

  data =[
    {id: "27",  name: "Burger King", sum: "900"}, 
    {id: "4",  name: "Eggs(4)", sum: "896"}, 
    {id: "5",  name: "Hamburger",  sum: "910"}, 
    {id: "8",  name: "Mac & Cheese", sum: "761"}, 
    {id: "56",  name: "McDonalds", sum: "1260"} 
 ];

我想提取总和的最大值并将其附加到li标签上.这是我的d3.js代码:

I want to extract the maximum value for the sum and append it to an li tag. This is my d3.js code:

 function add_max(){
 d3.select('#my_ul_tag).data(data).append('li')
    .text(function(d) { 
            return 'Max ' + d3.max(d.sum); 
    });

 }
    add_max();

这是从数组中的第一个对象(在上面的示例900中)获取值,然后将其视为数组,并提取最大值(在本例中为9).因此,如果值为785,那么它将返回8,因为它大于7和5.字符串"Max 8"将正确附加到ul,但是值"8"不正确.我正在寻找的最大值是1260.这对我来说很奇怪. 有人可以帮助我了解这个问题吗?谢谢!

What this does is gets the value from the first object in the array (in the above example 900) and then treats it like an array and extracts the maximum value, in this case 9. So, if the value was 785, then it would return 8 because it is larger than 7 and 5. The string "Max 8 " would be appended correctly to the ul, but the value "8" is not right. What I am looking for is the maximum value of 1260. That is strange to me. Can anybody help me understand this problem? Thank you!

推荐答案

您的属性是字符串,但是您希望将它们视为数字.清理整件事的正确的d3解决方案是:

Your properties are strings but you want to treat them as numbers. Cleaning this whole thing up the proper d3 solution is:

function add_max() {
  var maxValue = d3.max(data, function(d){
    return +d.sum; //<-- convert to number
  })
  d3.select('#my_ul_tag').append('li')
    .text(maxValue);
}

运行代码:

<!DOCTYPE html>
<html>

<head>
  <script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>

<body>
  
  <ul id="my_ul_tag"></ul>
  
  <script>
    var data = [{
      id: "27",
      name: "Burger King",
      sum: "900"
    }, {
      id: "4",
      name: "Eggs(4)",
      sum: "896"
    }, {
      id: "5",
      name: "Hamburger",
      sum: "910"
    }, {
      id: "8",
      name: "Mac & Cheese",
      sum: "761"
    }, {
      id: "56",
      name: "McDonalds",
      sum: "1260"
    }];

    function add_max() {
      var maxValue = d3.max(data, function(d){
        return +d.sum;
      })
      d3.select('#my_ul_tag').append('li')
        .text(maxValue);
    }
    
    add_max();
  </script>
</body>

</html>

这篇关于D3.js-如何获取对象中指定键的最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆