gpt4 book ai didi

javascript - 填补 NVD3.js 中的空白

转载 作者:行者123 更新时间:2023-11-30 05:38:06 27 4
gpt4 key购买 nike

我正在尝试在 NVD3.js 中制作水平分组堆叠条形图。一切都很好,直到我的 JSON 数据出现“差距”,如下所示:

 [{
"key": "Education & news",
"values": [{
"label": "2014-02-26",
"value": 702
}, {
"label": "2014-02-27",
"value": 204
}, {
"label": "2014-02-28",
"value": 3213
}]
}, {
"key": "Entertainment",
"values": [{
"label": "2014-02-26",
"value": 21
},
//Missing entry for 2014-02-27
{
"label": "2014-02-28",
"value": 3213
}]
}]

我得到的错误是 Uncaught TypeError: Cannot read property '1' of undefined in d3.js。我放在http://jsfiddle.net/vaa3V/上的问题的例子和错误

我能以某种方式自动填补空白吗?

最佳答案

@shabeer90 的评论正在进行中。您可以使用 underscore.js获取域值并应用合理的默认值。

//Find domain values
DEFAULT = 0
defaults = _.chain(data)
.pluck('values')
.flatten().pluck('label')
.uniq()
.value()
.map( function(item){ return {label:item, value:DEFAULT} })

// Group by 'label' so we can apply defaults
defaults = _.groupBy(defaults, 'label'))

// Apply defaults
_.each(data, function (series) {
grouped = _.groupBy(series.values, 'label')
series.values = _.flatten( _.defaults(grouped, defaults))
})

应该给你:

[
{
"key": "Education & news",
"values": [
{
"label": "2014-02-26",
"value": 702
},
{
"label": "2014-02-27",
"value": 204
},
{
"label": "2014-02-28",
"value": 3213
}
]
},
{
"key": "Entertainment",
"values": [
{
"label": "2014-02-26",
"value": 21
},
{
"label": "2014-02-28",
"value": 3213
},
{
"label": "2014-02-27",
"value": 0
}
]
}
]

关于javascript - 填补 NVD3.js 中的空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22351725/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com