How could i change my JSON structure into chartJS barchart JSON structure? - javascript

[
0: {flight: "Spicejet", range: "min", Jul 1: 2397, Jul 2: 2397, Jul 3: 2397},
1: {flight: "Spicejet", range: "max", Jul 1: 3045, Jul 2: 3045, Jul 3: 3045,},
2: {flight: "Spicejet", range: "med", Jul 1: 2789, Jul 2: 2789, Jul 3: 2789,},
3: {flight: "Indigo", range: "min", Jul 1: 3000, Jul 2: 3000, Jul 3: 3000,},
4: {flight: "Indigo", range: "max", Jul 1: 5000, Jul 2: 5000, Jul 3: 5000,},
5: {flight: "Indigo", range: "med", Jul 1: 4000, Jul 2: 4000, Jul 3: 4000,},
]
into
labels: ["Jul 1","Jul 2","Jul 3"],
datasets: [
{
label: "SpiceJet",
data: [3045,3045,3045],
},
{
label: "airways",
data: [5000,5000,5000],
},
]
for chartJS reactjs (Linechart). The chartjs is complicated in this case please give some solution in this. In datasets[ {data:[only get the range "max" value]} ]

While the question is quite unclear regarding the intended usage of the target format, the actual transformation for the example can easily be achieved.
If we assume all input elements share the same data properties (Jul * in this case), we can extract the labels from an arbitrary input element.
The data sets can be obtained by mapping the input data.
// a filter function to determine the data properties we're interested in
let dataPropertiesFilter = (k) => k !== "flight" && k !== "range";
let result = {
// this assumes the first element has all data properties set and subsequent ones share the same properties
labels: Object.keys(input[0]).filter(dataPropertiesFilter),
// transforms each input element into the target format
datasets: input.map(e => {
return {
label: e.flight,
data: Object.keys(e)
.filter(dataPropertiesFilter)
.map(v => e[v])
};
})
};
Here's a codesandbox for demonstration: https://codesandbox.io/s/stack-overflow-q-62406854-vzxnq?file=/src/index.js

Related

Unable to send array in a object via ajax post request. Array is not basically visible in the object after the after post requestsuccess

This is the Object which used in Post request#
ProductBrandName: "asd"
ProductCatagoryMenOrWomen: "Men"
ProductDiscription: "asd"
ProductImages: Array(1)
0: "https://firebasestorage.googleapis.com/v0/
1: "https://firebasestorage.googleapis.com/v0/
length: 2
__proto__: Array(0)
ProductName: "asd"
ProductPrice: "asd"
ProductType: "Shoes"
ProductUplodedDate: Wed Oct 14 2020 10:00:15{}
'''
After Post call, it is not displaying the array in the obj.
This is the obj after the post-call
I want an array in it
{
"id": "4",
"ProductName": "asd",
"ProductPrice": "asd",
"ProductDiscription": "asd",
"ProductCatagoryMenOrWomen": "Men",
"ProductBrandName": "asd",
"ProductUplodedDate": "Wed Oct 14 2020 10:00:15 GMT+0530 (India Standard Time)",
"ProductType": "Shoes"
}
This is the ajax call I am using to post it
$.ajax({
type:"post",
url:"https://5f844e4d6b9744002.mockapi.io/ShopingWebSit",
data:product
})

Setting maximum and minimum xScale values in Anychart graph results in an exception

I am creating a line chart using AnyChart
anychart.onDocumentReady(function() {
// create line chart
var dataSet = anychart.data.set([
[
"24 Apr 2019",
100.0
],
[
"24 Apr 2019", -100.0
],
[
"29 Apr 2019",
100.0
],
[
"29 Apr 2019",
100.0
],
[
"2 May 2019",
100.0
],
[
"2 May 2019", -100.0
],
[
"3 May 2019",
100.0
],
[
"6 May 2019", -100.0
],
]);
chart = anychart.line();
chart.animation(true);
chart.crosshair()
.enabled(true)
.yLabel(false)
.yStroke(null);
chart.tooltip().positionMode('point');
chart.legend()
.enabled(true)
.fontSize(13)
.padding([0, 0, 10, 0]);
var seriesData_1 = dataSet.mapAs({
'x': 0,
'value': 1
});
var series_1 = chart.line(seriesData_1);
series_1.name('Apple');
series_1.color("#335FAB");
series_1.hover().markers()
.enabled(true)
.type('circle')
.size(4);
series_1.tooltip()
.position('right')
.anchor('left-center')
.offsetX(5)
.offsetY(5);
chart.container('container');
chart.draw();
});
html,
body,
#container {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://cdn.anychart.com/releases/8.2.1/js/anychart-bundle.min.js"></script>
<div id="container"></div>
I need set the minimum and maximum xScale values for this graph. I have tried the following:
chart.xScale().minimum("2 April 2019");
chart.xScale().maximum("10 May 2019");
But that returns an exception:
TypeError: chart.xScale(...).minimum is not a function
The default xScale for the line chart is an ordinal scale. This scale type doesn't support min/max values as it represents logic categories. Your data is dateTime related, for this case the dataTime scale is more suitable.
You can apply dateTime scale to your chart and adjust min/max. Below is your modified JS code:
anychart.onDocumentReady(function() {
anychart.format.inputDateTimeFormat('dd MMM yyyy');
// create line chart
var dataSet = anychart.data.set([
[
"24 Apr 2019",
100.0
],
[
"24 Apr 2019", -100.0
],
[
"29 Apr 2019",
100.0
],
[
"29 Apr 2019",
100.0
],
[
"2 May 2019",
100.0
],
[
"2 May 2019", -100.0
],
[
"3 May 2019",
100.0
],
[
"6 May 2019", -100.0
],
]);
chart = anychart.line();
chart.animation(true);
chart.crosshair()
.enabled(true)
.yLabel(false)
.yStroke(null);
chart.tooltip().positionMode('point');
chart.legend()
.enabled(true)
.fontSize(13)
.padding([0, 0, 10, 0]);
var seriesData_1 = dataSet.mapAs({
'x': 0,
'value': 1
});
var series_1 = chart.line(seriesData_1);
series_1.name('Apple');
series_1.color("#335FAB");
series_1.hover().markers()
.enabled(true)
.type('circle')
.size(4);
series_1.tooltip()
.position('right')
.anchor('left-center')
.offsetX(5)
.offsetY(5);
//adjust xScale
var scale = anychart.scales.dateTime();
scale.minimum(anychart.format.parseDateTime('2 April 2019', 'dd MMM yyyy'));
scale.maximum(anychart.format.parseDateTime('10 May 2019', 'dd MMM yyyy'));
chart.xScale(scale);
chart.container('container');
chart.draw();
});
But if you really need the ordinal scale type, you can use a trick. Just add the following line to your code:
chart.xScale().values(['2 April 2019', '24 Apr 2019', '29 Apr 2019', '2 May 2019', '3 May 2019', '6 May 2019', '10 May 2019']);
You can learn more about scale types in the article.

Amcharts: How to pass title in balloonFunction?

I want to format the data before passing it would be shown as a tooltip. For this purpose I use balloonFunction and compareGraphBalloonFunction
"stockGraphs": [
{
"id": "g1",
"valueField": "value",
"comparable": true,
"compareField": "value",
"balloonFunction": this.ballonRender,
"compareGraphBalloonFunction": this.ballonRender,
// This is works
//"balloonText": [[title]]
//"compareGraphBalloonText": [[title]]
}]
But when I send a title as a parameter to my ballonRender function I can't find the property that shows the name of my graph among title object.
ballonRender(title) {
let sign = (title["percents"]["value"]>0) ? "+" : "-";
let values = (title["values"]["value"]).toFixed(4)
let percentage = (title["percents"]["value"]).toFixed(2)
let newTitle = 'Product <b>%s</b> (%s %s%)'.format(values, sign, percentage)
return newTitle
},
If I print title inside my ballonRender function I observe the following object.
category : Mon Oct 02 2017 00:00:00 GMT+0800 (Гонконг, стандартное время) {}
dataContext : amCategoryIdField: "1506873600000"
dataContext : {__ob__: Observer}
date : Mon Oct 02 2017 08:00:00 GMT+0800 (Гонконг, стандартное время) {}
rawData : (5) [{…}, {…}, {…}, {…}, {…}]
valueAbsHigh : 1.0477245421
valueAverage : 1.04665801056
valueClose : 1.0466455011
valueCount : 5
valueHigh : 1.0477245421
valueLow : 1.0451341501
valueOpen : 1.0451341501
valueSum : 5.2332900528
graph : {id: "g1", valueField: "value", comparable: true, compareField: "value", balloonFunction: ƒ, …}
index : 40
isNegative : false
percents : {value: 4.664550109999993, percents: 23.826681846132807, total: 339.27455273}
serialDataItem : {dataContext: {…}, category: Mon Oct 02 2017 00:00:00 GMT+0800 (Гонконг, стандартное время), time: 1506873600000, axes: {…}, x: {…}}
values : {value: 1.0466455011, percents: 23.826681846132807, total: 4.3927455273}
x : 608
y : 359.7633884380001
I can't understand why [[title]] in balloonText works fine, but when I pass this parameter to the function I can't retrieve the graphs title.
Also I'm a bit confused about input parameters in ballonFunction in general. It wound be nice if you share a resource with explanation and best-practicies.
The title comes from the graph object itself. In the stock chart's case, the graph inherits the title from the dataSet, but the same property is populated. All you have to do is access the graph object that is passed as a second parameter to the balloonFunction, which you don't have in your function currently, to get the title data:
"balloonFunction": function(graphDataItem, graph) {
return "<u>" + graph.title + "</u>: <b>" + graphDataItem.values.value + "</b>";
},
"compareGraphBalloonFunction": function(graphDataItem, graph) {
return "<u>" + graph.title + "</u>: <b>" + graphDataItem.values.value + "</b>";
}
Demo

d3js line graph not showing

I am working on creating a line graph and I am having a rather trivial issue. I am using d3js V4 and the specific code is as follows:
$(scope.container).append($('<svg id="svgimg" width="640" height="350" style="margin-left:auto;margin-right:auto;"></svg>'));
var mainGroup = d3.select("#svgimg").append("g");
d3.select("#svgimg").call(d3.zoom().on("zoom",function(){
mainGroup.attr("transform","translate(" + d3.event.transform.x+","+d3.event.transform.y+") scale ("+d3.event.transform.k+")" );
}));
var parseTime = d3.timeParse("%d-%y");
var svg = $("#svgimg"),
margin = {top:20,right:20,bottom:20,left:20},
width = +Number(svg.attr("width")) - margin.left -margin.right,
height = +Number(svg.attr("height")) - margin.top-margin.bottom,
g = mainGroup.append("g").attr("transform","translate("+margin.left+","+margin.top+")");
//console.log(width);
//console.log(height);
var n = 2000;
// random = d3.randomNormal(0,.2),
// data = d3.range(n).map(random);
var x =d3.scaleTime()
.domain([new Date(2017,10,1),new Date(2017,10,31)])
.range([0,width]);
var y = d3.scaleLinear()
.domain([0,2000])
.range([height,0]);
var line = d3.line()
.x(function(d,i){return x(parseTime(d.date));})
.y(function(d,i){return y(Number(+d.distance));});
g.append("defs").append("clipPath")
.attr("id","clip")
.append("rect")
.attr("width",width)
.attr("height",height)
g.append("g")
.attr("class","axis axis--x")
.attr("transform","translate(0,"+y(0)+")")
.call(d3.axisBottom(x))
g.append("g")
.attr("class","axis axis--y")
.call(d3.axisLeft(y))
g.append("g")
//.attr("clip-path","url(#clip)")
.append("path")
.datum(scope.data)
.attr("d",line)
.attr("class","linea");
svg.innerHTML = svg.innerHTML;
Where scope is an object (this) with a number of components.
Specifically, the line for the line graph is not visible while the side and bottom scales are. Further, upon inspection, the path element has the some associated data and if only I could see it, could begin debugging.
Any info would be greatly appreciated
Edit: The scope.data object contains an array of objects with time,date,distance and stamp fields. The graph "d" attribute is showing an X range from -25000 -> 25000 with a Y value of 155. I should be seeing a horizontal line from left side to right side but this is not happening. Also, I believe the time parsing to be the major culprit. The time value has been temporarily modified to be equal to a UTC datetime string.
Edit: The time is a UTC datetime string similar to:
Tue Sep 19 2017 09:33:42 GMT+1000 (AEST)
With rows differing by +- 10 minutes
I am currently using the following code:
var parseTime = d3.timeParse(d3.timeFormat.utc);
The complete array as from parsed json from browser
results
:
[{time: "Tue Sep 19 2017 09:33:42 GMT+1000 (AEST)", date: "11:00 AM",
distance: "1000", stamp: "0"},…]
0
:
{time: "Tue Sep 19 2017 09:33:42 GMT+1000 (AEST)", date: "11:00 AM",
distance: "1000", stamp: "0"}
1
:
{time: "Tue Sep 19 2017 09:23:42 GMT+1000 (AEST)", date: "11:00 AM",
distance: "1000", stamp: "0"}
2
:
{time: "Tue Sep 19 2017 09:13:42 GMT+1000 (AEST)", date: "11:00 AM",
distance: "1000", stamp: "0"}
3
:
{time: "Tue Sep 19 2017 09:03:42 GMT+1000 (AEST)", date: "11:00 AM",
distance: "1000", stamp: "0"}
4
:
{time: "Tue Sep 19 2017 08:53:42 GMT+1000 (AEST)", date: "11:00 AM",
distance: "1000", stamp: "0"}
5
:
{time: "Tue Sep 19 2017 08:43:42 GMT+1000 (AEST)", date: "11:00 AM",
distance: "1000", stamp: "0"}
6
:
{time: "Tue Sep 19 2017 08:33:42 GMT+1000 (AEST)", date: "11:00 AM",
distance: "1000", stamp: "0"}
7
:
{time: "Tue Sep 19 2017 08:23:42 GMT+1000 (AEST)", date: "11:00 AM",
distance: "1000", stamp: "0"}
8
:
{time: "Tue Sep 19 2017 08:13:42 GMT+1000 (AEST)", date: "11:00 AM",
distance: "1000", stamp: "0"}
I appologise for not posting earlier however, I felt it was irrelevant as no edits in any way have brought the path element into view.
#Gerado Furtado
Thank you for your patience, you may have answered the question without realising it. The answer was to ensure the "scope.data[].time" attribute was parsed with "new Date(scope.data[].time)" and the solution has worked. Thank you again, Patrick.

Converting JSON to an array

I have a variable that contains the following JSON string:
{
"0" : "Jun 20, 2012 03:02 PM",
"1" : "Jun 20, 2012 03:26 PM",
"2" : "Jun 21, 2012 01:12 PM",
"3" : "Jun 21, 2012 01:25 PM",
"4" : "Jun 21, 2012 02:42 PM",
"5" : "Jun 21, 2012 02:43 PM",
"6" : "NULL"
}
I wish to convert this JSON to an array in javascript such that
array[0] has "Jun 20, 2012 03:02 PM" array[1] has "Jun 20, 2012 03:26 PM" and so on.
You must parse your JSON string into a javascript object first.
JavaScript
var object = JSON.parse(JSONString);
To polyfill browsers without JSON support:
http://bestiejs.github.com/json3/
Then, convert that object to an array:
JavaScript
var arr = [];
for(var i in object) {
if(object.hasOwnProperty(i)) {
arr.push(object[i]);
}
}
jQuery
var arr = $.map(obj,function(value){ return value; });
Fiddle: http://jsfiddle.net/iambriansreed/MD3pF/
Note: Since the original poster did not mention jQuery it is worth mentioning that loading jQuery for only these instances isn't worthwhile, and you would be better off using the pure JavaScript if you aren't already using jQuery.
Alternatively, if you're targeting ES5 and above:
// myObject = { '0': 'a', '1': 'b' };
var myArray = Object.keys(myObject).map(function(key) { return myObject[key]; });
// myArray = [ 'a', 'b' ];
var currentVersion = {/literal} {$displayedVersion} {literal};
var jsonObj = eval('(' + {/literal}{$json}{literal} + ')');

Categories

Resources