如果数据不存在,如何用0填充数组?

时间:2017-09-19 08:24:53

标签: javascript angularjs chart.js

我正在使用chart.js的项目。使用chart.js我必须显示当月的月度利润图表。 数据来自服务器    第一个场景

    data:[0:{month :1 , profit :23}
        1:{month :2 , profit :678}
         .
         .
        0:{month :9 , profit :456}]

现在我想填补到12个月,利润为0,不包括有利润的月份

第二种情况

  data:[{0:{month :9 , profit :23}}]

这里我想从第1个月到第12个月填充数组,利润为零,不包括月份9,即sep如何做?

2 个答案:

答案 0 :(得分:2)

你可以玩这个Plunker,我认为它是一个很好的起点,你可以改进它并根据你的需要进行调整。

 while (i < 12){
    if(data[prev] && i == data[prev][prev].month) {
      array.push(data[prev][prev]);
      prev++;
    } else {
      array.push({i:{month: i, profit: 0}});
  }
i++;

}

所以这基本上就是你的函数所以你只需修改最终数组以匹配chart.js格式,希望这对你有所帮助

答案 1 :(得分:0)

查看this fiddle

要点: 基本上,清理您的数据。循环遍历数据并将所有数据推送到数组中。然后循环遍历一个12(12个月)的数组并将0放在阵列中找到一个洞的地方。

data.forEach(function (item) {
  // -> iterate over all keys in the item
  //    -> for every key get the month and profit and put into result
  //    -> result[month] = profit
});

现在填补空缺

// create an empty array of size 12
Array.apply(null, {length: 12 }).forEach(function (i, month) {
  // -> if result[month] == null
  //    -> that mean no data for that month is present.
  //    -> put that in the result with profit 0
  //    -> result[month] == 0
});

在图表中使用result数组。