How do I reshape my existing JSON to fit Highcharts - javascript

I am new to JS and I am having trouble with feeding my data to Highcharts for visualization.
Say I have a following JSON data
{
"is_error":0,
"keys":[
"count",
"created_date",
"source",
"gender_id",
"type"
],
"error":"",
"values":[
{
"count":3,
"created_date":"2017-08-09",
"source":"",
"gender_id":"",
"type":"Organization"
},
{
"count":1,
"created_date":"2017-08-10",
"source":"",
"gender_id":"",
"type":"Organization"
},
{
"count":2,
"created_date":"2017-08-09",
"source":"",
"gender_id":1,
"type":"Individual"
},
{
"count":1,
"created_date":"2017-08-12",
"source":"",
"gender_id":1,
"type":"Individual"
}
]
}
How would I transform it to a Highcharts series array so that it looks something like this:
series: [{
name: 'Organization',
data: [
[Date.UTC(2017, 08, 09), 3],
[Date.UTC(2017, 08, 10), 1],
]
}, {
name: 'Individual',
data: [
[Date.UTC(2017, 08, 09), 2],
[Date.UTC(2017, 08, 12), 1],
]
}]
In the JSON I have some information which isn't required (source and gender_id).
Here is my example in JSFiddle with full big data set that I want to transform using JS and fit it into a Highchart.
Is there an easy way to do transform a JSON like this to something which can be plugged into a Highchart?

Check this one Fiddle and update according to your needs
series: chartData

Related

Load data from json in tabulator?

I have this json variable and want to draw table by tabulator:
mydata=
[
{
"trade_symbol": "Media",
"technical_sum_List": [
19,
5,
4
],
"volume_sum_List": [
6,
1
],
"pivot_sum_list": [
5,
0,
0
]
},
{
"trade_symbol": "Sport",
"technical_sum_List": [
18,
4,
4
],
"volume_sum_List": [
3,
4
],
"pivot_sum_list": [
5,
0,
0
]
},
{
"trade_symbol": "Dance",
"technical_sum_List": [
13,
10,
5
],
"volume_sum_List": [
1,
6
],
"pivot_sum_list": [
2,
2,
0
]
}
]
Now I want to insert technical_sum_List[1] or technical_sum_List[2] in each columns by tabulator.
in tabulator we can only use field:"technical_sum_List" and do not accept technical_sum_List[1]!
There might be an easier way but you can do this through using a customFormatter. The gist is that when you define your table columns, you add a formatterParam which tells Tabulator which index in the array to reference and the name of the custom formatter function. Defining a separate function means you can reuse it for all your arrays.
{title:"B-1", field:"technical_sum_List", formatterParams: {index:0}, formatter: customFormatter},
Get the cell value and then use the formatterParams to reference and return the data at that array position.
function customFormatter(cell, formatterParams) {
return cell.getValue()[formatterParams.index];
}
let myData = [{
"trade_symbol": "Media",
"technical_sum_List": [
19,
5,
4
],
"volume_sum_List": [
6,
1
],
"pivot_sum_list": [
5,
0,
0
]
},
{
"trade_symbol": "Sport",
"technical_sum_List": [
18,
4,
4
],
"volume_sum_List": [
3,
4
],
"pivot_sum_list": [
5,
0,
0
]
},
{
"trade_symbol": "Dance",
"technical_sum_List": [
13,
10,
5
],
"volume_sum_List": [
1,
6
],
"pivot_sum_list": [
2,
2,
0
]
}
]
var table = new Tabulator("#example-table", {
height:"311px",
columns:[
{title:"A", field:"trade_symbol"},
{title:"B-1", field:"technical_sum_List",
formatterParams: {index:0},
formatter: customFormatter},
{title:"B-2", field:"technical_sum_List",
formatterParams: {index:1},
formatter: customFormatter},
{title:"B-3", field:"technical_sum_List",
formatterParams: {index:2},
formatter: customFormatter},
],
});
function customFormatter(cell, formatterParams) {
return cell.getValue()[formatterParams.index];
}
table.setData(myData);
<link href="https://unpkg.com/tabulator-tables#4.5.3/dist/css/tabulator.min.css" rel="stylesheet"/>
<script type="text/javascript" src="https://unpkg.com/tabulator-tables#4.5.3/dist/js/tabulator.min.js"></script>
<div id="example-table"></div>
#spring is right, you can only traverse object not arrays for column bindings.
#spring's approach may work, but you would have to be careful as filters and sorting would only see the array not the data.
A better approach would probably to use mutators, which would then make the data accessible to filters and sorters. so we can take #springs code and with a couple of tweaks make it work:
//define mutator
function customMutator(value, data, type, params) {
return data[params.field][params.index];
}
//assign mutator to columns
var table = new Tabulator("#example-table", {
height:"311px",
columns:[
{title:"A", field:"trade_symbol"},
{title:"B-1", field:"b1",
mutatorParams: {index:0, field:"technical_sum_List"},
mutator: customMutator},
{title:"B-2", field:"b2",
mutatorParams: {index:1, field:"technical_sum_List"},
mutator: customMutator},
{title:"B-3", field:"b3",
mutatorParams: {index:2, field:"technical_sum_List"},
mutator: customMutator},
],
});
This approach has several benefits, it means columns can be sorted and filtered and included in downloads.
It also means that now each column has its own unique field, so can be more easily looked-up from outside the table.
in summary formatters are visual only and DO NOT affect sorting and filtering. mutators on the other hand update the underlying data and DO affect sorting, filtering and everything else.
More details of this can be found in the Mutator Documentation
Thank you.
I found best answer:
We must use formatter: customFormatter
function customFormatter(cell, params) {
return cell.getValue()[params.myid].rvalue;
}
for(var r=0;r<alldata[0].result.length;r++){
table.addColumn({title:alldata[0].result[r].alias_title ,field:"result", formatterParams: {myid:r}, formatter: customFormatter});
}

How to use a javascript map functionality for multiple values

I have sensor data in the following format:
zdata =
{ "data": [
{
"timestamp": 10,
"sensor_id": 1,
"temp": 14.5,
"hum":13,
"light":11,
},
{
"timestamp": 20,
"sensor_id": 1,
"temp": 18,
"hum":12,
"light":20,
},
{
"timestamp": 5,
"sensor_id": 2,
"temp": 24.5,
"hum":12,
"light":15,
},
{
"timestamp": 20,
"sensor_id": 2,
"temp": 29.5,
"hum":12,
"light":2,
}
]
};
I using Chart js to display the sensor readings. The data I am using is coming from two different sensor_ids (sensor 1 and sensor 2), that may not necessarily have the same timestamps. Each sensor sends readings for light, humidity, and temperature. I need to plot the readings for both sensors on a graph against the time, so would need the above data like so:
Timestamps = [5, 10, 20]
Sensors = [1,2]
tempValueArray = [ [ '', 14.5, 18 ], [ 24.5, '', 29.5 ] ]
humidityValueArray = [ [ '', 13, 18 ], [ 24.5, '', 29.5 ] ]
lightValueArray = [ [ '', 13, 12 ], [ 12, '', 12 ] ]
Initially, I was just using a temperature sensor using a time map and the code posted as the answer here: Organising object data by timestep, so as to chart multiple sensor readings against time using Chart JS
However, I have updated the code here to loop through each type of reading (i.e. temp, hum, light):
var sensorNames = ['temp','hum','light'];
var allSensors = [];
for (i = 0; i < sensorNames.length; i++) {
let {sensors ,...sensorTimeMap} = zdata.data.reduce((acc,val) => {
sensorTypes = [val.temp, val.hum, val.light];
if(!acc[val.timestamp]) acc[val.timestamp] = {};
acc[val.timestamp][val.sensor_id] = sensorTypes[i];
if(!acc.sensors.includes(val.sensor_id))
acc.sensors.push(val.sensor_id)
return acc;
},{sensors:[]}); // get available sensors and create a timeStamp map for future iterations
let timestamp = Object.keys(sensorTimeMap);
allSensors.push(sensors.map(sensor => (Object.values(sensorTimeMap).map(obj => obj[sensor] || ''))));
};
console.log(sensors);
console.log(allSensors);
Is there a more efficient way to do this loop? I am new to javascript so am unsure how to add a number of readings in the map and save each to a new array.

Looking for a SMART json prettyprinter js library

I know ton of library can prettyprint json just by indenting/newline stuff but here is a line of my heavy json:
"Shape6":{"bounds_start":[0,-6,0],"bounds_end":[3,1,3],"origin":[2,15,-1],"mirror":true,"rotation":[0,0,0.837758],"uv":[15,30]}
All the libraries i found output something like this:
"Shape6": {
"bounds_start": [
0,
-6,
0
],
"bounds_end": [
3,
1,
3
],
"origin": [
2,
15,
-1
],
"mirror": true,
"rotation": [
0,
0,
0.837758
],
"uv": [
15,
30
]
}
But i'm looking for a more human-readable way which not add new lines for small arrays that can fit in a line like:
"Shape6": {
"bounds_start": [0, -6, 0],
"bounds_end": [3, 1, 3],
"origin": [2, 15, -1],
"mirror": true,
"rotation": [0, 0, 0.837758],
"uv": [15, 30]
}
i do want this because my json file is like 6k+ lines on the first example
if you know a js or a php library (for ajax purposes)
i thank you in advance (and sorry for my poor english :))
you can simply do that with using JSON.stringify() function (see the reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)
the first argument is the object you want to beautify, the second one is the function where we can specify the logic of line indention and new line breakings, the 3rd argument of this function (now 4) is the number for indention for your beautified JSON data
JSON.stringify(obj, function(k,v)
{
if (v instanceof Array)
return JSON.stringify(v);
return v;
}, 4);

How to push data to same array in java script in several time in same function?

I'm getting values from database in json structure. and i want to display them in table in javascript.Data come in following format.
"free_issue": [
{
"product_id": [14, 15, 16],
"free_product_ids": [15],
"structure": [
{
"req_qty": 10,
"free_qty": 2
},
{
"req_qty": 20,
"free_qty": 5
},
{
"req_qty": 50,
"free_qty": 10
}
]
}
From those data i want to push this data to table row. data in same row with 4 columns.I used array push method to push data. but i'm unable to get it in correct way.
in here all the data should in one row.
Please help me to do this.......
have You tried to do like this?
"free_issue": [
{
"product_id": [14, 15, 16],
"free_product_ids": [null, 15, null],
"structure": [
{
"req_qty": 10,
"free_qty": 2
},
{
"req_qty": 20,
"free_qty": 5
},
{
"req_qty": 50,
"free_qty": 10
}
]
}
I mean You've to generate these arrays before and then attach these arrays to fields of object. Notice: all of arrays must be same length to be able aligned to correct rows.

Create Highchart (Column chart) and read data from external json file

I have to create a column chart in my project using Highchart.I have JSON file that contain some data look like:
{
"meta": [
"rectime",
"strid",
"ambt",
"stri",
"b1",
"b2",
"b3",
"b4"
],
"data": [
[
1377597739,
1,
0,
77,
816,
13791,
13794,
13945
],
[
1377597739,
2,
0,
0,
816,
13744,
13725,
13898
]
]
}
May anyone can suggest me about what should I do.
ThanKs all helping
after you recieve the response (I mean the JSON) in success call back pass the response.data to a routine which will parse this JSON data as accepted by Highcharts.
series:[{
name: 'series 1'
data: [1,2,4,5,6,74]
},{
name: 'series 2'
data: [1,2,4,5,6,74]
},{
name: 'series 3'
data: [1,2,4,5,6,74]
}]
you can exclude name if you don't want to give a specific name to every series. although highcharts generates unique name for every series.
to get the column chart set the type to column.
chart:{
type: 'column'
}

Categories

Resources