Reputation: 1953
I am making a bar chart component which I import in my app.js
. My JSON data contains cricket match information i.e season
and runs
(i.e runs scored in that season). On Y-axis the height of bar will be sum of all the runs in particular season and on X-axis the labels would be the season.
For below JSON example:
season 2008 -> runs = 100+200=300
season 2009 -> runs = 300
season 2010 -> runs = 1100
season 2011 -> runs = 100
JSON data:
[
{
"season":2008,
"runs":100
},
{
"season":2008,
"runs":200
},
{
"season":2009,
"runs":300
},
{
"season":2010,
"runs":600
},
{
"season":2010,
"runs":500
},
{
"season":2011,
"runs":100
}
]
Chart component:
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;
Instead of hardcoding the data from JSON data how can I inject season
as labels
and runs
as series
. I tried using for loop but I was not able to get sum of runs for a particular season
. eg: for season 2008
it should be 100+200=300 i.e label=2008 and series element corresponding to it will be 300
.
Note: For given JSON data series will be :
series:[300, 300, 1100, 100]
Upvotes: 0
Views: 1921
Reputation: 11
Sharing my take on the task
<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>
Upvotes: 0
Reputation: 491
Create new array, loop through all elements of current array, parse them by their key and see if value is unique in our new array, if it's not add to that, if it is create new element.
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
});
}
Upvotes: 1
Reputation: 1
using array reduce to combine the seasons, and another reduce to create the two arrays
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)
Broken down in ES5, step by step
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);
Upvotes: 3