[英]Displaying JSON in Chart.js
我正在从本地文件中获取和解析 JSON 数据,并且我正在使用Chart.js来显示数据。 我想要显示的数据是给定单词的使用次数以及作为图表标签的单词。
问题:
我已经设法在wordCount
函数中获得了单词和出现对。 如果我注销counts
,我可以看到比赛。 我的痛点是如何正确显示我目前拥有的数据。 我看到其中一些显示出来,但它不正确。
代码:
var ctx = document.getElementById('myChart').getContext('2d');
const tweets = []
const counts = {}
const keyz = []
// Fetch JSON file locally and return the data
fetch('../test_feed.json')
.then(res => res.json())
.then(data => {
handleTweetText(data)
compare()
wordCount()
createChart()
})
.catch(err => console.error(err));
function handleTweetText(data) {
for (var i = 0; i < data.content.length; i++) {
const tweetHtml = data.content[i].content.bodyHtml;
// If tweet exists, return it
if(tweetHtml && tweetHtml != '') {
// Regex to grab entire anchor tag
const regEx = /<a(\s[^>]*)?>.*?<\/a>/ig
// Replace anchor with empty string and remove empty space
const splitTweetText = tweetHtml.replace(regEx, '').trim()
tweets.push(splitTweetText)
}
}
}
function wordCount() {
const allWords = tweets.join('\n')
const tokens = allWords.split(/\W+/)
for (let i = 0; i < tokens.length; i++) {
var word = tokens[i].toLowerCase()
if (counts[word] === undefined) {
counts[word] = 1
keyz.push(word)
} else {
counts[word] = counts[word] + 1
}
}
}
// sort word occurrence
keyz.sort(compare)
function compare(a ,b,) {
const countA = counts[a]
const countB = counts[b]
return countB - countA
}
// Chart
function createChart() {
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: keyz,
datasets: [{
label: 'Word Count',
data: keyz,
backgroundColor: [
'rgba(255, 99, 132, 0.2)'
],
borderWidth: 1
}]
}
})}
data
datasets
的labels
字段和data
字段是我需要放置配对数据的地方。
我已经在这方面工作了一段时间,但没有运气。
一方面, fetch
是异步的,所以你必须等待它完成。
这就是为什么你有then
方法。
但是,您正在尝试在keyz
有任何数据之前对keyz
进行排序。
将 sort 函数移动到then
方法中,
在填充wordCount
keyz
之后。
并自行调用compare
,什么都不做......
// Fetch JSON file locally and return the data
fetch('../test_feed.json')
.then(res => res.json())
.then(data => {
handleTweetText(data)
wordCount()
keyz.sort(compare)
createChart()
})
.catch(err => console.error(err));
但通常情况下,您不会对图表中的labels
和data
使用相同的数据。
您是否可能打算对图表中的data
使用counts
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.