首页 > 解决方案 > 在 React.js 中可视化谷歌分析数据,编辑 json

问题描述

我正在从谷歌分析中提取数据以显示在用户仪表板上。这是我在 React 中的第一个可视化项目,我决定使用 recharts 进行可视化。但是,我想重新格式化一些谷歌分析数据,使其看起来很漂亮,比如日期。

我正在努力编写一个函数来遍历我的数据数组并将数据 201903 重新格式化为例如 2019 年 3 月(或者更好的是 2019 年 3 月)。我只需要一个可以做到这一点的功能。但是,我没有从数组中提取此类数据的经验。

这是我的数据:

[ [ '201811', '1', 'DailyPrep', '2' ],
  [ '201812', '1', 'DailyPrep', '64' ],
  [ '201901', '1', 'DailyPrep', '220' ],
  [ '201902', '1', 'DailyPrep', '755' ],
  [ '201903', '1', 'DailyPrep', '8534' ],
  [ '201904', '1', 'DailyPrep', '4705' ],
  [ '201905', '1', 'DailyPrep', '3667' ] ]

我正在寻找的一个函数示例是:

Const FormatX = () => {
   //year = the first four digits of the first data item in each array
   //month = the last two digits of the first data item in each array
   //monthyr = month + ', ' + year;
   //return monthyr;
}

标签: javascriptreactjsdata-visualizationgoogle-analytics-apirecharts

解决方案


如果您只是在寻找日期格式化程序,您可以尝试 moment.js

moment("201905", "YYYYMM").format("MMMM YYYY");
// Output: May 2019

使用您发布的数据,您可能会遇到 recharts 问题,因为它只接受其中包含对象的数组(而不是像您的示例中那样的数组)。您需要将数组映射到一个对象。

const mapped = data.map(v => { return { date: v[0], someValue: v[3] } })

我将您的示例放在JSFiddle中,希望对您有所帮助。


推荐阅读