How to pass json data to highcharts series? - javascript

I have following json array which is generated at runtime.
Hence the number of name/data pairs varies.
`var sales = { "SalesData" : [
{ "name" : "AllProducts|Canada", "data" :[44936.0,50752.0] },
{ "name" : "AllProducts|Mexico", "data" : [200679.0,226838.0] },
{ "name" : "AllProducts|USA", "data" : [288993.0,289126.0] }
]} `
I want to pass this data to series in highcharts.
This is how I am doing it currently.
series: [
{name:sales.SalesData[0].name,data:sales.SalesData[0].data},
{name:sales.SalesData[1].name,data:sales.SalesData[1].data},
{name:sales.SalesData[2].name,data:sales.SalesData[2].data}
]
But if the number of elements in array are changed then this won't work.
How do I solve this problem ? Demo code will help me.
I have refereed following questions but I was not able to solve the problem.
Dynamically adding to Highcharts
Highcharts series data array

I solved the problem
Changed json array as follows:
var sales = [
{ "name" : "AllProducts123|Canada", "data" :[44936.0,50752.0] },
{ "name" : "AllProducts|Mexico", "data" : [200679.0,226838.0] },
{ "name" : "AllProducts|USA", "data" : [288993.0,289126.0] }
]
Now pass it directly to series in highcharts.
series:sales
Done !!!!!

Instead of constructing the series array manually you could loop through the sales variable data and construct the array. So what ever the number of elements in the sales.SalesData array, all items will be there in the series array
var series = [],
salesData= sales.SalesData;
for (var i=0 i< salesData.length; i++) {
series.push({"name" : key, "data" : sales[key]})
}
This constructed series array is part of the object which you must pass as argument to highcharts method.
var chartdata = {
chart: {type: 'column'},
title: {text: 'Sales Data'},
xAxis: {
categories: ['Category 1','Category 2']
},
yAxis: {
min: 0,
title: {text: 'Sales'}
},
series : []
}
chartdata.series = series;
$('#chart').highcharts(chartdata);
where #chart is the container where you want to display the chart.
you can also refer to the fiddles which are available in their demo pages for each type of chart to know more on how to display a particular type of chart.

Related

SAPUI5 Data binding for table not working

I am new into SAPUI5 development, and i have problems with data binding in a table. In my other tables it works but this one is strange.
I am opening a value helper dialog, and want to display some data in the table.
My current code is:
//
oTable = this._oValueHelpDialog.getTable();
oTable.setModel(this.getModel());
oTable.setModel(oCol, "columns");
// bind aggregation
// items
// shrhelpSet
// spalten heißen key und value
var oTemplate = new sap.m.ColumnListItem({
cells: [
new sap.m.Text({
text: "{key}"
}),
new sap.m.Text({
text: "{value}"
})]
});
oTable.bindAggregation("items", "/shrhelpSet", oTemplate);
My console says "Aggregation "items" does not exist in Element sap.ui.table.Table#__table0"
and when i am using a another binding method for example oTable.bindItems() or bindRows() it is saying that the method is undefinded or cannot be found.
i am suprised that i have this problem in the value helper, in my other tables i have no problems with data binding.
This worked for me and solved my problem
var aColumnData = [{
columnId: "Key"
}, {
columnId: "Value"
}];
var aData = [{
Key: "asdf",
Value: "hey"
}, {
Key: "abcd",
Value: "hey2"
}];
var oModel2 = new sap.ui.model.json.JSONModel();
oModel2.setData({
columns: aColumnData,
rows: aData
});
oTable.setModel(oModel2);
oTable.bindColumns("/columns", function(index, context) {
var sColumnId = context.getObject().columnId;
//alert(sColumnId);
return new sap.ui.table.Column({
id : sColumnId,
label: sColumnId,
template: sColumnId
});
});
oTable.bindRows("/rows");
The sap.m.Table has the aggregation "items", but in your case the table is a "sap.ui.table.Table" which uses the aggregation "rows". That is also the reason why the other methods don't work.
"ColumnListItem" won't work neither because the aggregation needs "sap.ui.table.Row".
For databinding, have a look at the example(s) for the grid table.

Filtering column's collection

In my Webix datatable one column fetches the data from the DataColletion. The problem is in the column's filtering: seems like it works with the original data (that contains the ID) and ignores the value of the data collection. How can I change this behavior and filter datatable by the collection's value?
Data:
var mycollection = new webix.DataCollection({
data:[{
id: '12',
value: 'CollItem 1'
}]
});
var mydata = [{
id: 1,
name: 'Item 1',
troublesomeColumn: '12' // id of the CollItem 1
}];
Config:
columns:[{
id: 'troublesomeColumn',
collection: mycollection,
header:{
content:"textFilter"
}
}],
data:mydata
Code snippet. Thanks in advance.
Filters work with the dataset, not with the templates or values from the linked collections. Therefore, you need to create a custom filtering rule as described in the Webix Docs, i.e. define the needed pattern in the compareproperty of the filter:
{
content:"textFilter",
compare:function(value, filter, obj){
var colValue = mycollection.getItem(value).value;
toFilter = colValue.toString().toLowerCase();
filter = filter.toString().toLowerCase();
return toFilter.indexOf(filter) !== -1;
}
}
Updated snippet

How to pass list in JavaScript?

I am trying to dynamically send a list object (as below) in JavaScript.
I am trying to setup a dynamic grid which accepts dynamic column names (instead of hardcoding the columns)
I am trying to create columnmap dynamically that will be used by grid, something like below,
columMap : {
'Header' : [
{ title : "Title", field : "Title" },
{ title : "Created", field : "Created" },
{ title : "Created By", field : "CreatedBy.Account" }
]
I tried with var list={field : 'Name',title:'Name'}.. This works fine for one column but does't work for multiple columns. I tried array too, didn't work.. Anyone has any suggestions?
[] represents an empty array
[1, 2, 3] is an array of three numbers
[ { a: 1 }, { a: 1 } ] is an array of objects
[ 1, "a", { a: 3 } ] an array does not care what type it holds
So...
var list =
[
{field : 'Name',title:'Name'}
];
Sorry, it was my mistake... I forgot to remove [] when I was passing my list object hence it was not able to set the value..
I got it resolved by passing list as below..
var list = [{ field: 'Name',title: 'Name' },{ field:'ContextNamePathRaw',title: 'Ownership Hierarchy'} ];
Thanks for your help!!!
BB

is there a way in Slick.Grid to render all data to an array so it can be exported?

Is there a way in Slick.Grid to render all data to an array so it can be exported?
I am able to get the data from my Slick.Grid instance "mygrid.getData().getItems()" but it is just the raw data not the formated data.
Is there a function I can use to iterate though the collection and return the formated data?
As of now I am having to implement my formatters twice.
Example:
UnixToDate: (row, cell, value, columnDef, dataContext) ->
moment.unix(value).format("MMM Do YY")
items: [
{id: 1, activity_at: 915148798 },
{id: 2, activity_at: 999148800 }
]
columns: [
{field: 'id', id: 'id', name: 'Id'},
{field: 'activity_at', id: 'activity_at', name: 'Activity', formatter: UnixToDate}
]
#data = new Slick.Data.DataView()
#grid = new Slick.Grid( $('#table'), #data, columns )
#data.setItems(items)
I am wondering if there is a way to return the data with the formatted values.
I thought #grid.getData().getItems() would do it but it returns the raw data array.
The data returned should look like:
data: [
{id: 1, activity_at: "Dec 31st 98" },
{id: 2, activity_at: "Aug 29th 01" }
]
I would like the end user to be able to filter and arrange the grid and then export the results in csv format, I have all this working except the formatting part.
Ok I wrote a method to do the export (written in coffeescript and using underscore.js). I also had to expose the getFormatter method in slick.grid.js
getFormattedData: (grid) ->
columns = grid.getColumns()
rows = grid.getData().getItems()
_(rows).map (row) ->
h = {}
i = 0
_(columns).each (column) ->
f = grid.getFormatter(row, column)
h[column.id] = f(row, i, row[column.id], column, row)
i += 1
h
add line to slick.grid.js in the // Public API section
"getFormatter": getFormatter,
When you set autoHeight: true the complete grid is rendered and the html could be exported.
http://mleibman.github.com/SlickGrid/examples/example11-autoheight.html
Answer to updated question:
The formatter is only called when a row is rendered/visible, so an array with the formatted data never exists. At the source: https://github.com/mleibman/SlickGrid/blob/master/slick.grid.js#L1291

knockoutjs highcharts parse arrays of data to chart

I am using a combination of highcharts and knockoutjs to feed data into my chart.
I have 4 massive arrays of data that need to be fed into my highchart upon a click event. I showed the data arrays empty here due to their huge size. Currently it returns an error like: Uncaught TypeError: Cannot read property 'metric' of undefined
My question is how do I access the areas.metric.data and parse it into my chart?
here is my (non) working fiddle:
http://jsfiddle.net/whiteb0x/BG8Qe/18/
function MetricsViewModel(areas) {
var self = this;
self.areas = [ // data structure
{
name: 'Game',
metrics: [{name : 'metric1', id : 'usdeur', data : []}, {name : 'metric2', id : 'msft', data : []}]
},
{
name: 'Player',
metrics: [{name : 'metric1', id : 'msft', data : []}, {name : 'metric2', id : 'msft', data : []}]
},
{
name: 'Social',
metrics: [{name : 'metric1', id : 'googl', data : [] }, {name : 'metric2', id : 'msft', data : []}]
}
];
series: [{ // default series
id: 'adbe',
data: ADBE
}]
}, function(chart){
var data = areas.metric.data; // corresponds to my object above ^^^
self.updateChart = function(metric) {
var id = this.id,
series = chart.get(id);
if(!series){
chart.addSeries({
id: id,
data: data
});
} else {
series.remove();
}
console.log(metric);
}
});
I'm not sure I understand you correctly, but according your code, this function declared in the ViewModel scope:
function(chart){
so you can access access both areas array and you observable metrics array like this:
var data = self.areas[0].metrics;
or observable metrics array like
self.metrics()
in any case, at the line where you have troubles, you are in ViewModel scope and can access whatever you want in it by this or self

Categories

Resources