javascript Array.push({y: yValue, label: myLabel}) setting random "x" key value - javascript

I am trying to create an canvasJS, JavaScript Bar Charts, with the following functions,
var dataPoints = [];
var headers;
var groups = [];
var cityWide = 0;
var chart = createChart();
function createChart(title = "Hospitalized Count") {
return new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
title:{
text:"Coronavirus Data in NYC Boroughs"
},
axisX:{
interval: 1
},
axisY2:{
interlacedColor: "rgba(1,77,101,.2)",
gridColor: "rgba(1,77,101,.1)",
title: "Total number of "+title
},
data: [{
type: "bar",
name: "companies",
axisYType: "secondary",
color: "#014D65",
dataPoints: dataPoints
}]
});
}
I am using this function below to set the dataPoints array:
function call: dataPoints = setDataPoints(4)
function setDataPoints(value){
let temp = [];
for(var i = 0; i<groups.length;i++){
if(groups[i][0] == "Citywide"){
continue;
}
yValue = groups[i][value];
myLabel = groups[i][0];
console.log("y: "+ yValue);
console.log("label: "+ myLabel);
temp.push(
{
y: yValue,
label: myLabel
});
}
console.log(temp);
return temp;
}
But when i console.log(dataPoints) I am getting this:
[
{"y": "136319","label": "Bronx","x": 0},
{"y": "202778","label": "Brooklyn","x": 1},
{"y": "97006","label": "Manhattan","x": 2},
{"y": "202737","label": "Queens","x": 3},
{"y": "54479","label": "StatenIsland","x": 4}
]
the expected result for dataPoints should be as follows:
[
{y:136319, label: "Bronx" },
{y:202778, label: "Brooklyn" },
{y:97006, label: "Manhattan" },
{y:202737, label: "Queens" },
{y:54479, label: "StatenIsland" }|
]
When I tried to set x
temp.push(
{
x: "123",
y: yValue,
label: myLabel
});
or delete temp[i]['x'] it doesn't work.
As you may of notice the x value are the indexes of the array, I have no idea why its being set and how do I even remove.
I have tried
dataPoints = temp;
console.log(dataPoints[0].hasOwnProperty('x'));
and returns false
Any help would appreciate it thanks in advance!
EDIT based of comment:
in for loop:
console.log(temp[i]['x']) returns undefined
If I add in to temp.push({ x: "123", ...})
console.log(temp[i]['x']) returns 123
console.log(temp[i]):
{y: "54479", label: "StatenIsland"}
label: "StatenIsland"
x: 4
y: "54479"
__proto__: Object
function.js:98

I'm not familiar with CanvasJS but my guess is that it's mutating the dataPoints array you give it to fill in the 'x' coordinate on the chart. console.log doesn't run synchronously, so by the time you see the output it's already been mutated.
If you console.log([...dataPoints]) or console.log([...temp]) I bet the x won't be there.
According to the API docs for dataPoints.x:
If not provided, it will be set automatically set according to its index position on dataPoints Array.
If you want to keep your "clean" copy of dataPoints you need to pass a copy of the array to the chart [...dataPoints].

Related

I am getting extra x value in array object using javascript

I am actually trying to display canvas.js chart using this json dynamically.
I have this result:
[{"s":40,"ProductName":"yoga pants"},
{"s":20,"ProductName":"trousers"},{"s":16,"ProductName":"shirts"},
{"s":10,"ProductName":"pants"},{"s":7,"ProductName":"RED"},
{"s":5,"ProductName":"Tank Top"}]
…which is a json string
I am getting this:
[{40: "yoga pants", x: 0},
{20: "trousers", x: 1},
{16: "shirts", x: 2},
{10: "pants", x: 3},
{7: "RED", x: 4},
{5: "Tank Top", x: 5}]
But i do not want this extra x: value. I am using this code:
var result1 = JSON.parse(result);
var reformattedArray = result1.map(function (o)
{
var obj = {};
obj[o.s] = o.ProductName;
return obj;
});
Thanks in advance
It appears to me that what is really happening is that your reformattedArray is fine, but you are subsequently piping it through charting software that is assigning the x: property, effectively indexing your data for the x axis of a chart.
Is it possible that the result you are reporting is not the result of your map, but rather the result of an additional step?

add value to object in array javascript

I have 2 arrays
var labels = ["DESKTOP","MOBILE","TABLET"]
var chartData = ["100","10","15"]
And I need to combine these into one array with objects
var myData = [{
label: DESKTOP,
value: 100},
{
label: MOBILE,
value: 10},
{
label: TABLET,
value: 15},
];
So far I've pushed labels into an array with new object
$.each(labels, function (index, item) {
myData.push({
label: item,
value: ''
});
});
I've done empty value, and now can't push value to an object in array. Just can't figure out how to push each value to new object in array. Help is much appreciated.
Thanks.
Data is sample only.
var labels = ["DESKTOP", "MOBILE", "TABLET"];
var chartData = ["100", "10", "15"];
var myData = [];
labels.forEach(function(e, i) {
myData.push({
label: e,
data: chartData[i]
})
})
document.write(JSON.stringify(myData));
How about:
$.each(labels, function (index, item) {
myData.push({
label: item,
value: chartData[index]
});
});

Javascript JSON not working after parsing

I need to get graph generated from Mysql database with help of PHP. I got nice application from (http://canvasjs.com). So, I created my own JSON format in variable element from PHP SESSION. It gies me no error when debugged, but no result.
Line number 34 - 37 gives me graph if I don't comment them. When comment them and replace with my own JSON which is variable element and does not give me graph. Gives me blank page.
I am new to JSON. Help me out with this.
Following are my codes.
var array = <?php echo json_encode($_SESSION["r_array"]); ?>;
var count = 0;
var element = '';
var title = 'Malware lab, TCRC, CTA';
for( var i in array) {
if ( count == 0 ) {
element += ‘{y: ‘+array[i]+’,’+’ indexLabel: “‘+i+'”}';
} else {
element += ‘, {y: ‘+array[i]+’,’+’ indexLabel: “‘+i+'”}';
}
count++;
}
var chart = new CanvasJS.Chart(“chartContainer”,
{
title: {
text: title
},
data: [
{ type: type,
dataPoints: [
/*
34 {y: 2, indexLabel: “Kaka'”},
35 {y: 3, indexLabel: “Blackberry”},
36 {y: 1, indexLabel: “Windows Phone”},
37 {y: 5, indexLabel: “Others”},*/
element,
]
}
]
});
chart.render();
Dumped array of $_SESSION["r_array"] as following
Array (
[Trojan] => 1
[Malware] => 3
[Backdoor] => 6
[Virus] => 2
[Bot] => 5
[Rootkit] => 7
[Worm] => 5
)
element must be an array, you are trying to create it as a string(with syntax errors)
var array = <? php echo json_encode($_SESSION["r_array"]); ?> ;
var count = 0;
var element = [];
var title = 'Malware lab, TCRC, CTA';
for (var i in array) {
element.push({
y: array[i],
indexLabel: i
})
count++;
}
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: title
},
data: [{
type: type,
dataPoints: element
}]
});
chart.render();
Demo: Fiddle
Yo need to pass array in correct Way
Use another variable datapoints = [];
and the push object into that array
var datapoints = [];
for( var i in array) {
datapoints.push({ y : array[i] , indexLabel : i});
}
and then use it as below
var chart = new CanvasJS.Chart(“chartContainer”,
{
title: {
text: title
},
data: [
{ type: type,
dataPoints: datapoints
}
]
});
chart.render();

Highcharts displaying additional information to each bubble points using array

I'm using a bubble chart. I represent "Ideas" in this chart. Each bubble is one specific idea with an X-value and a Y-value. What I need is the "Idea name" in the tooltip for each bubble as additional information.
I already know that you can do it as followed:
series: [{
data: [ { x : 1, y : 100, myIdea : 'Idea1' },
{ x : 2, y : 150, myIdea : 'Idea2' },
{ x : 5, y : 170, myIdea : 'Idea3' } ]
}]
But here comes the problem:
I used an array of this kind before:
dataArray [0][0] = 1; dataArray [0][1] = 100; dataArray [0][2] = 5;
dataArray [1][0] = 2; dataArray [1][1] = 150; dataArray [1][2] = 5;
coming from a loop.
My dataArray array then looked like that: [1,100,5], [2,150,5], ...
I gave that to the series like that:
series: [{
data: dataArray
}]
that worked perfectly!
How do I create an array in this expected format:
data: [ { x : 1, y : 100, myIdea : 'Idea1' },
{ x : 2, y : 150, myIdea : 'Idea2' },
{ x : 5, y : 170, myIdea : 'Idea3' } ]
Does this somehow work with associative arrays like that:
var myData= {
"x": "1",
"y": "100",
"myIdea": "idea1"
}
Btw, what is the best way to pass dynamic data for the bubblechart series?
You can loop over your current dataArray and build the new array like so:
var oldDataArray = [
[1, 100, 5],
[2, 150, 5]
];
var newDataArray = oldDataArray.map(function (row) {
return {
x: row[0],
y: row[1],
z: row[2]
};
});
console.log(newDataArray);

How to call a variable by a string value in jQuery?

I have a data set as
var data1 = {values:[
{ X: "33", Y: 12 },
....
]};
var data2 = { values:[
{ X: "Jan", Y: 2 },
...
]};
I want to load appropriate data set by
$(document).ready(function() {
$(".test").click(function(){
var data = $(this).val() // the value will be data1 or data2
// how can I make the data a JSON equal to data1 or data2 instead of
// assigning the static value of $(this).val() to it.
}
});
How can I create the var data from the static value?
Don't.
Have data1, data2 as properties of an object, and use the square bracket member operator to access them.
var dataset = {
data1: {
values: [{
X: "33",
Y: 12
}, ....]
}
data2: {
values: [{
X: "Jan",
Y: 2
}, ...]
};
}
var data = dataset[$(this).val()]
Although if your data1 and data2 are global variables, you could access them the same way from the window object.
var data = window[$(this).val()]
But an object like dataset is still nicer than a bunch of globals.

Categories

Resources