I am trying to create a chart using fusioncharts, I am using an AJAX query to get the data and below is how I'm generating the chart.
My problem is that fusion charts needs to see for example "value" : "1" where as I need to be able to use "0" : "1" because of my php below
My PHP Script to get logins for each hour of yesterday and today
$yesterdays_date = new datetime(date('d.m.Y',strtotime("-1 days")));
$query = "SELECT DATE(login_date) as date, HOUR(login_date) as hour, COUNT(*) as logins FROM logins WHERE login_date >= '".$yesterdays_date->format('Y-m-d')."' GROUP BY DATE(login_date), HOUR(login_date)";
//storing the result of the executed query
$result = $conn->query($query);
//initialize the array to store the processed data
$jsonArray = array();
$array = array(
'today' => array(
"seriesname" => "Logins Yesterday",
"data" => array(
'0' => 0,
'1' => 0,
'2' => 0,
'3' => 0,
'4' => 0,
'5' => 0,
'6' => 0,
'7' => 0,
'8' => 0,
'9' => 0,
'10' => 0,
'11' => 0,
'12' => 0,
'13' => 0,
'14' => 0,
'15' => 0,
'16' => 0,
'17' => 0,
'18' => 0,
'19' => 0,
'20' => 0,
'21' => 0,
'22' => 0,
'23' => 0,
),
),
'yesterday' => array(
"seriesname" => "Logins Today",
"renderAs" => "line",
"showValues" => "0",
"data" => array(
'0' => 0,
'1' => 0,
'2' => 0,
'3' => 0,
'4' => 0,
'5' => 0,
'6' => 0,
'7' => 0,
'8' => 0,
'9' => 0,
'10' => 0,
'11' => 0,
'12' => 0,
'13' => 0,
'14' => 0,
'15' => 0,
'16' => 0,
'17' => 0,
'18' => 0,
'19' => 0,
'20' => 0,
'21' => 0,
'22' => 0,
'23' => 0,
),
),
);
//check if there is any data returned by the SQL Query
if ($result->num_rows > 0) {
//Converting the results into an associative array
while($row = $result->fetch_assoc()) {
if($row['date'] == $yesterdays_date->format('Y-m-d')){
//- Yesterdays data
$array['yesterday']['data'][$row['hour']] = $row['logins'];
}else{
//- Todays data
$array['today']['data'][$row['hour']] = $row['logins'];
}
//$jsonArrayItem = array();
//$jsonArrayItem['date'] = $row['date'];
//$jsonArrayItem['hour'] = $row['hour'];
//$jsonArrayItem['logins'] = $row['logins'];
//append the above created object into the main array.
//array_push($jsonArray, $jsonArrayItem);
}
}
//set the response content type as JSON
header('Content-type: application/json');
//output the return value of json encode using the echo function.
echo json_encode($array);.
My Data returned from the PHP script
My jQuery to generate the chart comparing yesterdays logins with today
function getLogins(){
$.ajax({
url: '/ajax/getLoginsToday.php',
type: 'GET',
success: function(data){
var chartProperties = {
"caption": "Product-wise quarterly revenue Vs profit in last year",
"subCaption": "Harry's SuperMart",
"xAxisname": "Quarter",
"yAxisName": "Login Total",
"paletteColors": "#0075c2,#1aaf5d,#f2c500",
"bgColor": "#ffffff",
"borderAlpha": "20",
"showCanvasBorder": "0",
"usePlotGradientColor": "0",
"plotBorderAlpha": "10",
"legendBorderAlpha": "0",
"legendShadow": "0",
"legendBgAlpha": "0",
"valueFontColor": "#ffffff",
"showXAxisLine": "1",
"xAxisLineColor": "#999999",
"divlineColor": "#999999",
"divLineDashed": "1",
"showAlternateHGridColor": "0",
"subcaptionFontBold": "0",
"subcaptionFontSize": "14",
"showHoverEffect": "1"
};
apiChart = new FusionCharts({
type: 'stackedcolumn2dline',
renderAt: 'chartContainer',
width: '550',
height: '350',
dataFormat: 'json',
dataSource: {
"chart": chartProperties,
"categories": [
{
"category": [
{
"label": "00-01"
},
{
"label": "01-02"
},
{
"label": "02-03"
},
{
"label": "03-04"
},
{
"label": "04-05"
},
{
"label": "05-06"
},
{
"label": "06-07"
},
{
"label": "07-08"
},
{
"label": "08-09"
},
{
"label": "09-10"
},
{
"label": "10-11"
},
{
"label": "11-12"
},
{
"label": "12-13"
},
{
"label": "13-14"
},
{
"label": "14-15"
},
{
"label": "15-16"
},
{
"label": "16-17"
},
{
"label": "17-18"
},
{
"label": "18-19"
},
{
"label": "19-20"
},
{
"label": "20-21"
},
{
"label": "21-22"
},
{
"label": "22-23"
},
{
"label": "23-24"
}
]
}
],
"dataset": [
{
"seriesname": "Logins Yesterday",
"data": data
},
{
"seriesname": "Logins Today",
"renderAs": "line",
"showValues": "0",
"data": [
{
"value": "24000"
},
{
"value": "45000"
},
{
"value": "23000"
},
{
"value": "38000"
}
]
}
]
}
});
apiChart.render();
}
});
}
In my jQuery AJAX success block above you can see i'm trying to set the dataset via the AJAX data but fusioncharts needs to see it like "value":"1"
whereas my data is formatted like "0":"1", "23":"4".
What's my best solution to get it into the format that fusioncharts wants?
You might try with Array.map().
The code above will let you convert this:
[15,15,16,17,18,19,20,21,22,25,30,32,28,15,14,15,15,10,8,7,8,9,10,10]
to this:
[{"value":15},{"value":15},{"value":16},{"value":17},{"value":18},{"value":19},{"value":20},{"value":21},{"value":22},{"value":25},{"value":30},{"value":32},{"value":28},{"value":15},{"value":14},{"value":15},{"value":15},{"value":10},{"value":8},{"value":7},{"value":8},{"value":9},{"value":10},{"value":10}]
Explanation:
var yesterdayData = [15,15,16,17,18,19,20,21,22,25,30,32,28,15,14,15,15,10,8,7,8,9,10,10];
var yesterday = []; // Declare a new variable to expose the results in the graph.
yesterdayData.map(function(x) { // x contains the current value.
yesterday.push({"value": x}); // For every item in the array, push the current value to the yesterday array variable.
});
Something like this:
$(function() {
function getLogins() {
$.ajax({
url: "https://gist.githubusercontent.com/dannyjhonston/4ef6fae2e6142606578c080aec4cd690/raw/04ab3a73f4a07defbd67de6b9e8ffaf47ea61862/fusioncharts.json",
type: "GET",
success: function(data) {
data = JSON.parse(data);
var yesterdayData = data.yesterday.data; // Data from the server.
var yesterday = [], todayData = data.today.data; // Data from the server.
var today = [];
yesterdayData.map(function(x) {
yesterday.push({
"value": x
});
});
todayData.map(function(x) {
today.push({
"value": x
});
});
var chartProperties = {
"caption": "Product-wise quarterly revenue Vs profit in last year",
"subCaption": "Harry's SuperMart",
"xAxisname": "Quarter",
"yAxisName": "Login Total",
"paletteColors": "#0075c2,#1aaf5d,#f2c500",
"bgColor": "#ffffff",
"borderAlpha": "20",
"showCanvasBorder": "0",
"usePlotGradientColor": "0",
"plotBorderAlpha": "10",
"legendBorderAlpha": "0",
"legendShadow": "0",
"legendBgAlpha": "0",
"valueFontColor": "#ffffff",
"showXAxisLine": "1",
"xAxisLineColor": "#999999",
"divlineColor": "#999999",
"divLineDashed": "1",
"showAlternateHGridColor": "0",
"subcaptionFontBold": "0",
"subcaptionFontSize": "14",
"showHoverEffect": "1"
};
var apiChart = new FusionCharts({
type: 'stackedcolumn3dline',
renderAt: 'chartContainer',
width: '550',
height: '350',
dataFormat: 'json',
dataSource: {
"chart": chartProperties,
"categories": [{
"category": [{
"label": "00-01"
}, {
"label": "01-02"
}, {
"label": "02-03"
}, {
"label": "03-04"
}, {
"label": "04-05"
}, {
"label": "05-06"
}, {
"label": "06-07"
}, {
"label": "07-08"
}, {
"label": "08-09"
}, {
"label": "09-10"
}, {
"label": "10-11"
}, {
"label": "11-12"
}, {
"label": "12-13"
}, {
"label": "13-14"
}, {
"label": "14-15"
}, {
"label": "15-16"
}, {
"label": "16-17"
}, {
"label": "17-18"
}, {
"label": "18-19"
}, {
"label": "19-20"
}, {
"label": "20-21"
}, {
"label": "21-22"
}, {
"label": "22-23"
}, {
"label": "23-24"
}]
}],
"dataset": [{
"seriesname": "Logins Yesterday",
"data": today // The required data goes here.
}, {
"seriesname": "Logins Today",
"renderAs": "line",
"showValues": "0",
"data": yesterday // The required data goes here.
}]
}
});
apiChart.render();
}
});
}
getLogins();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
<script src="https://static.fusioncharts.com/code/latest/fusioncharts.charts.js"></script>
<div id="chartContainer">FusionCharts will render here</div>
Hope this helps.
Related
const array = [
{
"data": {
"qty": "5",
"toy": {
"id": 3,
},
"available": "yes",
}
},
{
"data": {
"qty": "5",
"toy": {
"id": 10,
},
"available": "no"
}
},
{
"data": {
"qty": "59",
"toy": {
"id": 10,
},
"available": "yes",
}
},
{
"data": {
"qty": "5",
"toy": {
"id": 3,
},
"available": "yes",
}
}
]
var result = [];
array.reduce(function(res, value) {
if (!res['data']['toy'] || !res['data']['toy']['data']) {
res['data'] = {...value['data'] };
result.push(res['data'])
}
if (res['data']['available'] === value['data']['available'] && res['data']['toy']['id'] === value['data']['toy']['id']) {
res['data']['qty'] = parseInt(res['data']['qty']) + parseInt(value['data'].qty)
}
return res;
}, {'data': {}});
console.log(result)
I am working on a js project and I need a bit of help here. From the array, How to get a new array that has qty as the sum of the other qty value which data.toy.id and available same. i.e. I want the below array. My code is not working as excepted. Changes to the same or new code are also fine. Thank you.
const array = [
{
"data": {
"qty": "10",
"toy": {
"id": 3,
},
"available": "yes",
}
},
{
"data": {
"qty": "5",
"toy": {
"id": 10,
},
"available": "no"
}
},
{
"data": {
"qty": "59",
"toy": {
"id": 10,
},
"available": "yes",
}
}
]
You group the array into an object, where the keys are concatenation of available and id properties and finally transform the object back to an array using Object.values.
const
array = [
{ data: { qty: "5", toy: { id: 3 }, available: "yes" } },
{ data: { qty: "5", toy: { id: 10 }, available: "no" } },
{ data: { qty: "59", toy: { id: 10 }, available: "yes" } },
{ data: { qty: "5", toy: { id: 3 }, available: "yes" } },
],
result = Object.values(
array.reduce((r, { data }) => {
const k = data.available + data.toy.id;
if (r[k]) {
r[k].data.qty = String(Number(r[k].data.qty) + Number(data.qty));
} else {
r[k] = { data };
}
return r;
}, {})
);
console.log(result);
I'd suggest using Array.reduce() to group by a key, which will be combined value of the toy id and the available property.
We'd create a map of all toys based on this key, summing the quantity for each.
Finally, we'll use Object.values() to convert back into an array.
const array = [ { "data": { "qty": "5", "toy": { "id": 3, }, "available": "yes", } }, { "data": { "qty": "5", "toy": { "id": 10, }, "available": "no" } }, { "data": { "qty": "59", "toy": { "id": 10, }, "available": "yes", } }, { "data": { "qty": "5", "toy": { "id": 3, }, "available": "yes", } } ];
const result = Object.values(array.reduce((acc, { data: { qty, toy, available } }) => {
const key = `${toy.id}-${available}`;
acc[key] = acc[key] || { data: { qty: 0, toy, available } };
acc[key].data.qty += Number(qty);
return acc;
}, {}))
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }
You can use Array#reduce() to create arrayHash object using as keys: ${c.data.toy.id}-${c.data.available}
Code:
const array = [{data: {qty: '5',toy: {id: 3,},available: 'yes',},},{data: {qty: '5',toy: {id: 10,},available: 'no',},},{data: {qty: '59',toy: {id: 10,},available: 'yes',},},{data: {qty: '5',toy: {id: 3,},available: 'yes',},},]
const arrayHash = array.reduce((a, { data }) => {
const key = `${data.toy.id}-${data.available}`
a[key] = a[key] || { data: { ...data, qty: 0 } }
a[key].data.qty = (+a[key].data.qty + +data.qty).toString();
return a
}, {})
const result = Object.values(arrayHash)
console.log(result)
I'd use just reduce
const a1 = [
{
"data": {
"qty": "5",
"toy": {
"id": 3,
},
"available": "yes",
}
},
{
"data": {
"qty": "5",
"toy": {
"id": 10,
},
"available": "no"
}
},
{
"data": {
"qty": "59",
"toy": {
"id": 10,
},
"available": "yes",
}
},
{
"data": {
"qty": "5",
"toy": {
"id": 3,
},
"available": "yes",
}
}
]
const a2 = a1.reduce((acc, it) => {
let found = acc.find(
dp => dp.data.toy.id === it.data.toy.id && dp.data.available === it.data.available
)
if(found){
found.data.qty = ( Number(found.data.qty) + Number(it.data.qty) ).toString()
}
else acc.push(it)
return acc
}, [])
console.log(JSON.stringify(a2, null,2))
I'm learning Javascript and getting started with React. I'm attempting to build a Materials-UI's DataGrid and need to structure my data accordingly. I have the following piece of code that prepares the Rows and Columns for DataGrid but I feel it may be "slow" and wondering if I can get the community's input on how it can be written more efficiently. Any ideas/solutions would be appreciated. Thanks.
input:
const values = [
{
"documentId": "12345",
"documentDirectory": "Canadian PnC",
"properties": [
{
"name": "HoldingNumber",
"type": "STRING",
"value": "88888",
},
{
"name": "DocumentType",
"type": "STRING",
"value": "TAC",
},
{
"name": "DocumentName",
"type": "STRING",
"value": "Income",
},
]
},
{
"documentId": "54321",
"documentDirectory": "Wealth",
"properties": [
{
"name": "HoldingNumber",
"type": "STRING",
"value": "99999",
},
{
"name": "DocumentType",
"type": "STRING",
"value": "TAC",
},
{
"name": "DocumentName",
"type": "STRING",
"value": "Appraisal",
},
]
}
];
output:
//console.log(cols);
[
{
field: "DocumentDirectory", headerName: "DocumentDirectory", width: 200
},
{
field: "DocumentId", headerName: "DocumentId", width: 200
},
{
field: "HoldingNumber", headerName: "HoldingNumber", width: 200
},
{
field: "DocumentType", headerName: "DocumentType", width: 200
},
{
field: "DocumentName", headerName: "DocumentName", width: 200
}
]
//console.log(rows);
[
{
id: 0,
DocumentDirectory: "Canadian PnC",
DocumentId: "12345",
HoldingNumber: "88888",
DocumentType: "TAC",
DocumentName: "Income"},
{
id: 1,
DocumentDirectory: "Wealth",
DocumentId: "54321",
HoldingNumber: "99999",
DocumentType: "TAC",
DocumentName: "Appraisal"
}
]
I'm currently achieving it the using the following:
const docDirectory = values.map(result => result.documentDirectory);
const docId = values.map(result => result.documentId);
const docProperties = values.map(result => result.properties);
let cols= [];
let rows= [];
for (let i = 0; i < docProperties.length; i++) {
const p = docProperties[i];
let o = {};
o["id"] = i;
o["DocumentDirectory"] = docDirectory[i];
o["DocumentId"] = docId[i];
if (i === 0) {
cols.push({ field: "DocumentDirectory", headerName: "DocumentDirectory", width: 200 });
cols.push({ field: "DocumentId", headerName: "DocumentId", width: 200 });
}
for (let j = 0; j < p.length; j++) {
let nam = p[j].name;
let val = p[j].value;
o[nam.replace(/\s+/, "")] = val;
if (i === 0) {
cols.push({ field: nam.replace(/\s+/, ""), headerName: nam, width: 200 });
}
}
rows.push(o);
}
console.log(cols);
console.log(rows);
const values = [
{
documentId: '12345',
documentDirectory: 'Canadian PnC',
properties: [
{
name: 'HoldingNumber',
type: 'STRING',
value: '88888'
},
{
name: 'DocumentType',
type: 'STRING',
value: 'TAC'
},
{
name: 'DocumentName',
type: 'STRING',
value: 'Income'
}
]
},
{
documentId: '54321',
documentDirectory: 'Wealth',
properties: [
{
name: 'HoldingNumber',
type: 'STRING',
value: '99999'
},
{
name: 'DocumentType',
type: 'STRING',
value: 'TAC'
},
{
name: 'DocumentName',
type: 'STRING',
value: 'Appraisal'
}
]
}
];
const cols = [
{
field: 'DocumentDirectory',
headerName: 'DocumentDirectory',
width: 200
},
{
field: 'DocumentId',
headerName: 'DocumentId',
width: 200
},
...values[0].properties.map(p => ({
field: p.name,
headerName: p.name,
width: 200
}))
];
const rows = values.map((value, index) => {
return {
id: index,
DocumentDirectory: value.documentDirectory,
DocumentId: value.documentId,
...value.properties.reduce(
(val, cur) => ({
...val,
[cur.name]: cur.value
}),
{}
)
};
});
console.log(cols);
console.log(rows);
const values = [{
"documentId": "12345",
"documentDirectory": "Canadian PnC",
"properties": [{
"name": "HoldingNumber",
"type": "STRING",
"value": "88888",
},
{
"name": "DocumentType",
"type": "STRING",
"value": "TAC",
},
{
"name": "DocumentName",
"type": "STRING",
"value": "Income",
},
]
},
{
"documentId": "54321",
"documentDirectory": "Wealth",
"properties": [{
"name": "HoldingNumber",
"type": "STRING",
"value": "99999",
},
{
"name": "DocumentType",
"type": "STRING",
"value": "TAC",
},
{
"name": "DocumentName",
"type": "STRING",
"value": "Appraisal",
},
]
}
];
const allCols = values.reduce((prev, { documentDirectory, properties }) => ([
...prev,
{ field: documentDirectory, headerName: documentDirectory, width: 200 },
...properties.map(({name: field, name: headerName}) => ({field, headerName, width: 200}))
]), [])
const cols = [...new Set(allCols.map(JSON.stringify))].map(JSON.parse)
console.log(cols)
const rows = values.reduce((prev, next) => ([
...prev,
...next.properties.map(property => ({
DocumentDirectory: next.DocumentDirectory,
DocumentId: next.DocumentId,
...property
}))
]), []).map((row, key) => ({id: key, ...row}))
console.log(rows)
i'm trying to create a Charts.js with stacked bars from a json list of objects, with no success...
my json is
[{
"machine": {
"machineId": 1,
"name": "a",
"description": "aaaaaa",
"active": true,
"direction": "IN"
},
"realEnergy": 56.99,
"lastUpdate": "2018-10-16 09:00:00"
}, {
"machine": {
"machineId": 2,
"name": "ABCD 1",
"description": "ABCD 1",
"active": true,
"direction": "OUT"
},
"realEnergy": 62.11,
"lastUpdate": "2018-10-16 09:00:00"
}, {
"machine": {
"machineId": 1,
"name": "M1",
"description": "Machine M1",
"active": true,
"direction": "IN"
},
"realEnergy": 57.11,
"lastUpdate": "2018-10-16 09:30:00"
}, {
"machine": {
"machineId": 2,
"name": "ABCD 1",
"description": "ABCD 1",
"active": true,
"direction": "OUT"
},
"realEnergy": 62.14,
"lastUpdate": "2018-10-16 09:30:00"
}, {
"machine": {
"machineId": 1,
"name": "M1",
"description": "Machine M1",
"active": true,
"direction": "IN"
},
"realEnergy": 58.18,
"lastUpdate": "2018-10-16 10:00:00"
}, {
"machine": {
"machineId": 2,
"name": "ABCD 1",
"description": "ABCD 1",
"active": true,
"direction": "OUT"
},
"realEnergy": 71.11,
"lastUpdate": "2018-10-16 10:00:00"
}, {
"machine": {
"machineId": 1,
"name": "M1",
"description": "Machine M1",
"active": true,
"direction": "IN"
},
"realEnergy": 64.11,
"lastUpdate": "2018-10-16 10:30:00"
}, {
"machine": {
"machineId": 2,
"name": "ABCD 1",
"description": "ABCD 1",
"active": true,
"direction": "OUT"
},
"realEnergy": 72.11,
"lastUpdate": "2018-10-16 10:30:00"
}]
I would like to have lastUpdate on the labels and stacked realEnergy values for the bars.
I was trying to adopt this json to match Charts.js dataset with no luck.
var size = Object.keys(json).length ;
labels = response.map(function(e) {
return e.lastUpdate;
});
for(var i = 0; i < size; i++){
datasetValue[i] = {
fillColor: 'rgba(220,220,220,0.5)',
strokeColor :'rgba(220,220,220,1)',
label :json[i].machine.name,
data : json[i].realEnergy
}
}
var myData = {
datasets : datasetValue
}
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets:myData
},
options: {
scales: {
yAxes: [{
stacked: true
}],
xAxes: [{
stacked: true
}]
}
}
});
}
I can get the labels correctly but no data on it, cannot understand how the dataset values should be created.
Dataset's data property is an array of values that will be distributed across the labels (in this case realEnergy value per each lastUpdate). I assume that each dataset should represent particular machine.
Here's the code to generate datasets and labels based on your JSON data:
const jsonData = JSON.parse(yourJSONData);
const colors = ['yellow', 'green', 'blue']; // purely optional
const machines = jsonData.reduce((uniqueMachines, record) => {
// find unique machines that will be base to our datasets
if (!uniqueMachines.find(machine => machine.machineId === record.machine.machineId))
uniqueMachines.push(record.machine);
return uniqueMachines;
}, []);
const lastUpdates = jsonData.reduce((uniqueLastUpdates, record) => {
// get labels for our chart
if (!uniqueLastUpdates.find(lastUpdate => lastUpdate === record.lastUpdate))
uniqueLastUpdates.push(record.lastUpdate);
return uniqueLastUpdates;
}, []);
const datasets = machines.map((machine, index) => {
const label = machine.name;
const backgroundColor = colors[index]; // purely optional
const data = lastUpdates.map(lastUpdate => {
const valueRecord = jsonData.find(record => record.machine.machineId === machine.machineId && record.lastUpdate === lastUpdate);
if (!valueRecord) return 0; // if value record is not defined, return 0;
return valueRecord.realEnergy;
});
return {
// here we return dataset
label,
backgroundColor,
data,
stack: 'main' // here we define the stack
};
});
And here's the final configuration for the chart:
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: lastUpdates,
datasets
},
options: {
scales: {
yAxes: [{
stacked: true
}]
}
}
});
A working example on the JSFiddle: click
I have json like
SampJson= [
{
data: "50",
cIndex: "column0",rowno:"1"
},
{
data: "5",
cIndex: "column1",rowno:"1"
},
{
data: "80",
cIndex: "column0",rowno:"2"
},
{
data: "65",
cIndex: "column1",rowno:"2"
}
];
I need to create a JSON like
[
{
rowno:1,
column0:50,
column1:5
},
{
rowno:2,
column0:80,
column1:65
}
];
Thanks in advance...
You should just do this:
sampJson = [
{
data: "50",
cIndex: "column0",
rowno: "1"
},
{
data: "5",
cIndex: "column1",
rowno: "1"
},
{
data: "80",
cIndex: "column0",
rowno: "2"
},
{
data: "65",
cIndex: "column1",
rowno: "2"
}
];
var results = [];
sampJson.forEach(function(el) {
if (results[+el.rowno - 1] == null) {
results[+el.rowno - 1] = new Object();
}
results[+el.rowno - 1].rowno = +el.rowno;
results[+el.rowno - 1][el.cIndex] = +el.data;
});
console.log(results);
I want to add a for loop to my FusionChart script, so i can enter values through the loop. but so far i could not do it. please help. this is the code. what can i do to make this loop work?
FusionCharts.ready(function () {
var revenueChart = new FusionCharts({
type: 'column3d',
renderAt: 'chartContainer',
width: '500',
height: '300',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Monthly revenue for last year",
"subCaption": "Harry's SuperMart",
"xAxisName": "Month",
"yAxisName": "Revenues (In USD)",
},
"data": [
//for (var i = 0; i < ist.length; i++) {// this is where i want to add the loop
{
"label": ist[0].MyProperty_Test_Customer_Id,
"value": parseFloat(ist[0].MyProperty_Test_Chargers)
},
{
"label": ist[1].MyProperty_Test_Customer_Id,
"value": parseFloat(ist[1].MyProperty_Test_Chargers)
},
{
"label": ist[2].MyProperty_Test_Customer_Id,
"value": parseFloat(ist[2].MyProperty_Test_Chargers)
}
//}
]
}
});
revenueChart.render();
});
OK, so the data attribute needs to be an array. You can achieve this with a for loop if it is inside of a so-called IIFE and having the IFFE return an array (note that you would put the following inside the chart configuration):
"data": (function() {
var data = [];
for (var i = 0; i < ist.length; i++) {
data.push({
"label": ist[i].MyProperty_Test_Customer_Id,
"value": parseFloat(ist[i].MyProperty_Test_Chargers)
})
}
return data;
})()
Better yet, create the array you need using the for loop above var revenueChart = new FusionCharts({...:
var chartData = [];
for (var i = 0; i < ist.length; i++) {
chartData.push({
"label": ist[i].MyProperty_Test_Customer_Id,
"value": parseFloat(ist[i].MyProperty_Test_Chargers)
})
}
var revenueChart = new FusionCharts({
...
data: chartData
...
FusionCharts.ready(function () {
var data = [];
//alert(x.length);
for (var i = 0; i < x.length; i++) {
data.push({
"label": x[i].HR_BG,
"value": x[i].b
})
}
var ageGroupChart = new FusionCharts({
type: 'pie3d',
renderAt: 'chart-pie',
width: '600',
height: '500',
dataFormat: 'json',
dataSource:
{
"chart": {
"caption": "YTR Production Hours",
"subCaption": "",
"paletteColors": "#0075c2,#1aaf5d,#f2c500,#f45b00,#8e0000",
"bgColor": "#ffffff",
"showBorder": "0",
"use3DLighting": "0",
"showShadow": "0",
"enableSmartLabels": "0",
"startingAngle": "0",
"showPercentValues": "0",
"showPercentInTooltip": "0",
"decimals": "",
"captionFontSize": "14",
"subcaptionFontSize": "14",
"subcaptionFontBold": "0",
"toolTipColor": "#ffffff",
"toolTipBorderThickness": "0",
"toolTipBgColor": "#000000",
"toolTipBgAlpha": "80",
"toolTipBorderRadius": "2",
"toolTipPadding": "5",
"showHoverEffect":"1",
"showLegend": "1",
"legendBgColor": "#ffffff",
"legendBorderAlpha": '0',
"legendShadow": '0',
"legendItemFontSize": '10',
"legendItemFontColor": '#666666'
},
"data": data
}
}).render();
});