如何从 json 中提取数据并将其注入图表?

How to extract data from json and inject it into chart?

我正在制作一个条形图组件,我将其导入 app.js。我的 JSON 数据包含板球比赛信息,即 seasonruns(即那个赛季的得分)。在 Y 轴上,条形图的高度将是特定季节中所有运行的总和,而在 X 轴上,标签将是季节。

下面的JSON例子:

season 2008 -> runs = 100+200=300
season 2009 -> runs = 300
season 2010 -> runs = 1100
season 2011 -> runs = 100

JSON数据:

[
    { 
      "season":2008,
      "runs":100
    },
    { 
      "season":2008,
      "runs":200
    },
    { 
      "season":2009,
      "runs":300
    },
    { 
      "season":2010,
      "runs":600
    },
    { 
      "season":2010,
      "runs":500
    },
    { 
      "season":2011,
      "runs":100
    }   
]

图表组件:

import React, { Component } from 'react';
import ChartistGraph from 'react-chartist';

const ChartData = {

  //labels are the season

  labels: [ ],

  series: [
    // runs will be injected here
  ],
   distributeSeries: true
}

const options = {
    width: 720,
    height: 400
}

class Chart extends Component {

  render(){
    return(
      <div>
         <ChartistGraph data={ChartData} type={'Bar'} options={options}/>
      </div>
    )}

}

export default Chart;

我如何才能将 season 作为 labelsruns 作为 series 注入,而不是对来自 JSON 数据的数据进行硬编码。我尝试使用 for 循环,但无法获得特定 season 的运行总和。例如:对于 season 2008 它应该是 100+200=300 即 label=2008 和它对应的系列元素将是 300.

注意:对于给定的 JSON 数据系列将是:

series:[300, 300, 1100, 100]

使用数组 reduce 组合季节,并使用另一个 reduce 创建两个数组

var json = `[
    { 
      "season":2008,
      "runs":100
    },
    { 
      "season":2008,
      "runs":200
    },
    { 
      "season":2009,
      "runs":300
    },
    { 
      "season":2010,
      "runs":600
    },
    { 
      "season":2010,
      "runs":500
    },
    { 
      "season":2011,
      "runs":100
    }   
]`

var data = Object.entries(JSON.parse(json).reduce((acc, {season, runs}) => (acc[season] = (acc[season] || 0) + runs, acc), {}))
    .reduce((acc, [labels, series]) => (acc.labels.push(labels), acc.series.push(series), acc),{labels: [], series:[]}) 
    console.log(data)

在 ES5 中逐步分解

var json = `[
    { 
      "season":2008,
      "runs":100
    },
    { 
      "season":2008,
      "runs":200
    },
    { 
      "season":2009,
      "runs":300
    },
    { 
      "season":2010,
      "runs":600
    },
    { 
      "season":2010,
      "runs":500
    },
    { 
      "season":2011,
      "runs":100
    }   
]`
var data = JSON.parse(json); // because JSON is a string representation of an javascript object
var data1 = data.reduce(function (acc, item) {
    var season = item.season,
        runs = item.runs;
    acc[season] = acc[season] || 0; // add a season as a key
    acc[season] += runs; // add runs
    return acc;
}, {});
console.log(data1); 
var data2 = Object.entries(data1); // make an array of [[label, runs],[label, runs]...]
console.log(data2); 
var data3 = data2.reduce(function (acc, item) { // each item is an array of [year, total runs]
    var labels = item[0],
        series = item[1];

    acc.labels.push(labels);
    acc.series.push(series); 
    return acc;
}, { labels: [], series: [] }); // initialise the return object
console.log(data3);

创建新数组,遍历当前数组的所有元素,通过键解析它们并查看值在我们的新数组中是否唯一,如果不添加到那个,如果它是创建新元素。

function fillGraph(data){
var newArray = []; //creating new, empty array
    for(var i = 0; i < data.length; i++){ //going through all elements of data array
        if(newArray.hasOwnProperty(data[i]["season"]){ //if it already has that season
            newArray["season"] += data[i]["runs"]; //add runs to the current season
        }else{
            newArray.push({data[i]["season"] : data[i]["runs"]}); //if not create new object with key name as a season name and assign runs
        }
    }
    for(var i in newArray) { //go through our new array
        chartData.labels.push(i); //push key name of current array element into graph labels property
        chartData.series.push(newArray[i]); //push value of current array element into graph series property
    });
}

分享我对任务的看法

 <script>
            // in the url variable I use a link to my JSON, so might try you by 
            // firstly uploading your JSON at myjson.com
            let url = 'https://api.myjson.com/bins/8x9l7'; 

            fetch(url).then(res => res.json()).then((out) => {
                // here you might try console.log(out); to check the correctness of 
                // displaying your JSON imported via URL
                convertJsonToData(out);
            }).catch(err => { throw err });

            let data = {
                    labels: [],
                    series: [[]]
                };

            function convertJsonToData(jsonData) { 
                for (let x in jsonData) {
                    data.labels.push(jsonData[x].transactTime); //transactTime and walletBalance are keys in my JSON, you will have yours
                    data.series[0].push(jsonData[x].walletBalance);
                };
                // here you might try console.log(data); to check the correctness of 
                // data display taken from JSON and modified to use in chart
                return data;
            };

             let options = {
                 showPoint: false,
                 lineSmooth: true,
                 fullWidth: true,
                 height: 700,
                 showArea:true,
            };

             new Chartist.Line('.ct-chart', data, options);

          </script>