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

时间:2018-06-06 01:52:17

标签: javascript reactjs chartist.js

我正在制作一个条形图组件,我在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]

3 个答案:

答案 0 :(得分:2)

使用数组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);

答案 1 :(得分:1)

创建新数组,循环遍历当前数组的所有元素,按键解析它们,看看我们的新数组中值是否唯一,如果它没有添加,如果它是创建新元素。< / p>

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
    });
}

答案 2 :(得分:0)

分享我的任务

 <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>