如何将属性与对象数组中的值进行比较?

时间:2018-09-28 07:47:33

标签: javascript arrays for-loop d3.js

d {"children":[{"name":"China","children":[{"name":"China","value":400,"percentage":"33.33"}],"index":0},{"name":"England","children":[{"name":"England","value":300,"percentage":"33.33"}],"index":1},{"name":"Malaysia","children":[{"name":"Malaysia","value":500,"percentage":"25.00"}],"index":2},{"name":"South Korea","children":[{"name":"South Korea","value":600,"percentage":"50.00"}],"index":3}]}

对象数组

cfg.thresholdSetting.thresholds = [{"dType":"threshold","from":0,"to":30,"color":"rgb(217, 20 ,39)"},{"dType":"threshold","from":30,"to":70,"color":"rgb(242, 145, 10)"},{"dType":"threshold","from":70,"to":120,"color":"rgb(33, 145, 49)"}]

然后我有一个属性:

rect.style("fill", function (d, i) {

    for (var k = 0; k < fromValues.length; k++) {
      console.log("percentage : " + d.percentage)
      console.log("from value : " + fromValues[k])
      console.log("to value : " + toValues[k])
         if (d.percentage >= fromValues[k] && d.percentage <= toValues[k]) {
           return cfg.thresholdSetting.thresholds[k].color;
         }
         else {
           return "#808080";
         } 
    }
  })

从代码中,我的from和to值的输出停滞不动。外循环根据我拥有的数据数量运行。如何比较这些值?

当前输出

enter image description here

预期产量

d.percentage = 33.33
from value   = 0
to value     = 30

d.percentage = 33.33
from value   = 30
to value     = 70

d.percentage = 33.33
from value   = 70
to value     = 120 

d.percentage = 50.00
from value   = 0
to value     = 30

d.percentage = 50.00
from value   = 30
to value     = 70

d.percentage = 50.00
from value   = 70
to value     = 120

1 个答案:

答案 0 :(得分:0)

根据您的示例,假设您使用的是d3,并且您想根据矩形的颜色设置矩形的颜色。当数据与任何bin都不匹配时,我还假设"#808080"是默认颜色。在这种情况下:

rect.style("fill", function(d) {
    var color = cfg.thresholdSetting.thresholds.filter(function(t, i) {
        return d.percentage >= t.from && d.percentage < t.to;
    });
    return color.length > 0 ? color[0].color : "#808080";
});