将数据添加到动态创建的Chart.js数据集

时间:2017-06-06 17:59:05

标签: jquery arrays json chart.js

我觉得我非常接近,但我似乎无法做到最后一点。我尝试使用来自JSON文件的动态数据集在Chart.js中创建折线图。

我的JSON如下:

{
  "source":"Google Trends",
  "keywords":
  [
    {
      "value":"Keyword 1",
      "data":
      [
        {
          "month":"Dec",
          "popularity":"10"
        },
        {
          "month":"Jan",
          "popularity":"35"
        }
      ]
    },
    {
      "value":"Keyword 2",
      data:
      [
        ...
      ]
    }
  ]
}

然后我有以下jQuery:

var source = "Google Trends";
var trendDataset = [];
var trendData = [];

$.each(jsonFile, function(index, trends) {
  if (trends.source === source) {
    $.each(trends.keywords, function(index, keyword) {

      trendDataset[index] = {
        label: keyword.value,
        data: trendData,
        borderWidth: 1,
        backgroundColor: randomColor(),
        lineTension: 0
      }

    });
  }
});

这很好用,它为JSON文件中的每个关键字创建一个新数据集。但是我在填写这些数据集时遇到了麻烦。

我试图传递一个数据数组(trendData []),其中填充了每个关键字的流行度数据。我知道我需要遍历每个关键字的数据数组,所以我在现有循环中添加了这个$​​ .each循环:

$.each(keyword.data, function(index, data) {
  trendData.push(data.popularity);
});

总计创建:

$.each(jsonFile, function(index, trends) {
  if (trends.source === source) {
    $.each(trends.keywords, function(index, keyword) {

      trendDataset[index] = {
        label: keyword.value,
        data: trendData,
        borderWidth: 1,
        backgroundColor: randomColor(),
        lineTension: 0
      }

      $.each(keyword.data, function(index, data) {
        trendData.push(data.popularity);
      });

    });
  }
});

显然,这是添加所有关键字的所有流行度数据,创建一个大的trendData []。用trendData [index] = data.popularity替换trendData.push(data.popularity)做了正确的事情,但同样,显然只针对最后一个关键字,因为它一直被覆盖。

如何为每个trendDataset []创建一个单独的trendData []?

我想在第二个$ .each中我需要这样的东西:

$.each(keyword.data, function(index, data) {
  trendData[index] = data.popularity;
  trendDataset[index].push(trendData);
});

然而,这给了我一个错误:trendDataset [index] .push不是函数

编辑: 一步一步地走过它,这是不合理的,这是行不通的。它遍历第一个数组一次,创建第一个数据集。然后它循环通过第二个数组三次,然后该模式重复。

我需要能够在第一个数组中访问第二个数组的属性,如下所示:

trendDataset[index] = {
  data: trendData.data.popularity
}

但是怎么......?

EDIT2: 我越是想找到一个解决方案,我就越无能为力。每当我将console.log trendData设置为这样之后:

$.each(keyword.data, function(index, data) {
  trendData[index] = data.popularity;
});

console.log(trendData);

它显示具有正确值3次的对象,但在打开它时只显示最后一次迭代的值???

Screenshot

1 个答案:

答案 0 :(得分:0)

我终于明白了。这比我想象的容易得多,我不知道为什么我没有早点解决这个问题。

只需在第一个$ .each循环中创建单独的数组并设置值..

var trendDataset = [];

$.each(trends.keywords, function(index, keyword) {
  // Create an Array for each data object
  trendData = [];
  trendLabels = [];
    $.each(keyword.data, function(index, data) {
      trendLabels[index] = data.month,
      trendData[index] = data.popularity
    });  
  // Push the array with data to another array
  trendDataset[index].data = trendData;
});