Load data from json in tabulator? - javascript

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

Related

Mongo Query - $group

Is it possible with Mongo to make this transformation (with a $group I think) ?
or should it be done with JavaScript on the client side ?
[
{
id: 1,
lib: 'x'
},
{
id: 2,
lib: 'a'
},
{
id: 1,
lib: 'b'
},
{
id: 1,
lib: 'v'
}
]
to
[
{
id: 1,
lib_1: 'x',
lib_2: 'b',
lib_3: 'v'
},
{
id: 2,
lib_1: 'a'
}
]
Query
with $group you can easily put them in an array, and i think its best to just do this
but if you want the exact output like in your expected output its more complicated, because you need to convert array to object, and add numbers in keys etc, in general in mongodb fields are not made for data, because queries become harder, fields are for the schema
Playmongo
aggregate(
[{"$group": {"_id": "$id", "libs": {"$push": "$lib"}}},
{"$set":
{"libs":
{"$map":
{"input": {"$range": [0, {"$size": "$libs"}]},
"in":
{"k": {"$concat": ["lib_", {"$toString": {"$add": ["$$this", 1]}}]},
"v": {"$arrayElemAt": ["$libs", "$$this"]}}}}}},
{"$set": {"libs": {"$arrayToObject": ["$libs"]}}},
{"$replaceRoot": {"newRoot": {"$mergeObjects": ["$libs", "$$ROOT"]}}},
{"$project": {"libs": 0}}])

Querying an array in JSON with nested arrays in Postgres via sequelize

I have a complicated structure of a field in a column. I'm using Postgres#11 and sequilize#4.38.
This is my model:-
id: {
type: Sequelize.BIGINT,
primaryKey: true,
autoIncrement: true
},
extra: {
type: Sequelize.JSONB,
defaultValue: {}
}
This is the structure of extra column:-
{
"contentAreas": [
{
"name": "Foundations - Part 1",
"moments": [
157,
159,
160,
161
],
},
{
"name": "Foundations - Part 2",
"moments": [
163,
164,
165,
166,
167
]
}
],
}
I've an array of ids that I need to be queried on extra.contentAreas.moments. If an moment that is present in my array, it that is also present in the contentAreas.moments, I want to fetch that document.
This is my array:- [4, 56, 33, 161].
Any help will be appreciated. Thanks!
I tried this:- SELECT COUNT(*) as count FROM "public"."simulation" WHERE "extra.contentAreas" #> "moments" IN (2,34,3), but it is giving an error - column "extra.contentAreas" does not exist, because for some documents their is no contenAreas. Any suggestions on this?

Plotly.js multiple subplots not working as expected

Edit to add: Looking for the "plotly.js" way to do this. This "small multiple" visualization should have some "plotly.js" solution out there but haven't found it yet.
I am using an array (example element below) to populate traces for plotly.js multiple subplots per their multiple-subplots example
[{
"key": "Ontario|Toronto",
"values": [{
"key": "2020-01-25",
"value": 1
}, {
"key": "2020-01-27",
"value": 1
}, {
"key": "2020-05-12",
"value": 218
}, {
"key": "2020-05-13",
"value": 169
}]
}, {
etc
}]
The array has 94 elements which contain info needed to create each trace. This would result in 94 subplots, one per trace. This plotly.js visualization could also be called "small multiples".
I am creating the traces dynamically and populating subplot definitions in a loop using code below:
// create chart data
var traces = [];
var rowCount = (caseRegionByDate.length / 2).toFixed()
for (var i=0; i<caseRegionByDate.length; i++) {
//console.log(caseRegionByDate[i]['key']);
var trace = {};
var x = [];
var y = [];
for (var j=0; j<caseRegionByDate[i]['values'].length; j++) {
//console.log(caseRegionByDate[i]['values'][j]['key']);
x.push(caseRegionByDate[i]['values'][j]['key']);
y.push(caseRegionByDate[i]['values'][j]['value']);
}
// create trace i
trace = {
"x":x,
"y":y,
"xaxis":"x"+i,
"yaxis":"y"+i,
"type":"scatter"
}
// push trace to traces
traces.push(trace);
}
console.log(JSON.stringify(traces));
var layout = {
grid: {rows: rowCount, columns: 2, pattern: 'independent'},
};
Plotly.newPlot('multiple_charts', traces, layout);
This creates the traces variable populated by each trace that looks like example below. It looks correct:
[{
"x": ["2020-03-16", "2020-03-23", "2020-03-24", "2020-03-25", "2020-03-31", "2020-04-01", "2020-04-02", "2020-04-03", "2020-04-06", "2020-04-07", "2020-04-08", "2020-04-09", "2020-04-10", "2020-04-11", "2020-04-13", "2020-04-14", "2020-04-15", "2020-04-16", "2020-04-17", "2020-04-18", "2020-04-21", "2020-04-22", "2020-04-23", "2020-04-24", "2020-04-25", "2020-04-26", "2020-04-27", "2020-04-28", "2020-04-29", "2020-04-30", "2020-05-01", "2020-05-02", "2020-05-03", "2020-05-04", "2020-05-05", "2020-05-06", "2020-05-07", "2020-05-08", "2020-05-09", "2020-05-10", "2020-05-11", "2020-05-12", "2020-05-13"],
"y": [1, 1, 1, 1, 9, 35, 3, 16, 33, 13, 9, 5, 5, 1, 22, 3, 4, 7, 19, 4, 7, 2, 18, 11, 9, 9, 9, 13, 1, 3, 7, 18, 5, 4, 4, 5, 3, 1, 2, 2, 3, 1, 2],
"xaxis": "x0",
"yaxis": "y0",
"type": "scatter"
}, {
"x": ["2020-03-14", "2020-03-26", "2020-03-27", "2020-04-02", "2020-04-06", "2020-04-09", "2020-04-14", "2020-04-17", "2020-04-18", "2020-04-20", "2020-04-22"],
"y": [1, 1, 1, 2, 2, 3, 1, 1, 1, 2, 1],
"xaxis": "x1",
"yaxis": "y1",
"type": "scatter"
},
etc
]
However, the result appears to be one row with two columns that have all of the traces (there are 94 traces) squashed into them. Here is screenshot.
Any ideas what is happening? I expect to have 48 rows with 2 columns, one subplot per trace.
The only difference from the multiple subplots example is that my xaxis have date strings instead of numbers. Everything else is same.
The subplots are actually being created in 3 x rowCount grid. However they are all squashed vertically as in screenshot.
It appears that a chart's default height and width dimensions, where they are not explicitly defined using layout.height, are what is shown in my screenshot eg too small for 94 subplots.
The quick fix is to simply increase the chart's layout.height size. Then all subplots are visible. Dynamically calculating layout.height, in spirit of Juan's suggestion, relative to number of rows works well.
Apparently it is also possible to set each subplot's x and y domain attributes to resize subplots which will also give desired results.

Sort internal array timestamps

I have an array with multiple elements that looks like this:
{
"name": "DR",
"data": [
[
"1508112000000",
4
],
[
"1534204800000",
1
]
],
"type": "areaspline"
},
{
"name": "SIT",
"data": [
[
"1508112000000",
4
],
[
"1534204800000",
1
],
[
"1506384000000",
3
],
[
"1534204800000",
1
],
[
"1531094400000",
1
],
[
"1528502400000",
1
]
],
"type": "areaspline"
},
This is the exact format I use to send data into high charts, however, the problem is that the chart breaks if the timestamps inside each environment (DR, SIT) are not in order.
How can I sort the 'data' inside each environment by timestamp?
This JSON is generated in PHP and sent through to JavaScript. So I would like to know how to sort the data inside either PHP or JavaScript.
Thanks.
This is actually rather trivial, once you know about the usort function. It allows you to define your own sorting function, so you can sort based on any factor of whatever the 2 objects it is passed.
Note that from your example json I had to add a set of square brackets around the whole thing to get PHP to parse it with json_decode .
<?php
// note I had to add square brackets to your
// demo json ....
$json='[{
"name": "DR",
"data": [
[
"1508112000000",
4
],
[
"1534204800000",
1
]
],
"type": "areaspline"
},
{
"name": "SIT",
"data": [
[
"1508112000000",
4
],
[
"1534204800000",
1
],
[
"1506384000000",
3
],
[
"1534204800000",
1
],
[
"1531094400000",
1
],
[
"1528502400000",
1
]
],
"type": "areaspline"
}]';
$json_obj_arr=json_decode($json,true);
print_r($json_obj_arr);
print("\n\n");
// a function to handle the sorting itself
// usort will pass it an array(timestamp,datavalue) for both
// $a and $b so we compare the [0] element of each
function cmp($a, $b)
{
if ($a[0] == $b[0]) {
return 0;
}
return ($a[0] < $b[0]) ? -1 : 1;
}
// loop through the array, first is indexed
for($i=0;$i<count($json_obj_arr);$i++){
// then each one of those contains an
// associtive array with an element named ['data'] -
// this is an indexed array that you want sorted
// on the [0] element
usort($json_obj_arr[$i]['data'],"cmp");
}
print_r($json_obj_arr);
print("\n\n");
?>

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.

Categories

Resources