Manipulating array to add through setData on highcharts - javascript

I have the following data:
var data = {"categories":["GLA Age: 65+"],"series":[{"name":"Hendon","data":[11.98]},{"name":"High Barnet","data":[17.86]},{"name":"Mill Hill","data":[13.73]},{"name":"Oakleigh","data":[17.42]},{"name":"Totteridge","data":[17.76]}]};
I need the 'names' to be the categories names so I'm using 'events > load' to apply this to the highcharts code:
var seriesData = this.series;
var tCategories = [];
for (i = 0; i < seriesData.length; i++) {
tCategories.push(seriesData[i].name);
}
this.xAxis[0].setCategories(tCategories);
Then I need to set the 'data' into one array like
[11.98, 17.86, 13.73, 17.42, 17.76]
The problem I've come across is that the first lot of data shows in the first bar:
example here: http://jsfiddle.net/zidski/13rexxyo/3/
The code to create the new array ([11.98, 17.86, 13.73, 17.42, 17.76])
var arrayofArrays = data.series.map(function (item) {
return JSON.stringify([item.data]);
});
var seriesString = arrayofArrays;
seriesString = seriesString;
var n = JSON.stringify(seriesString).replace(/\[|]|"/g, '');
var g = '[' + n + ']';
var h = JSON.stringify(g);
var seriesC = JSON && JSON.parse(g) || $.parseJSON(g);
this.series[0].setData(seriesC);

It seems like it's being over-complicated, if I understand correctly (though your desired outcome is not entirely clear).
You can loop through the JSON and return a data array easily enough without using stringify or anything like that, and without needing a load event:
Code:
var title = rawData.categories[0];
var chartData = []
$.each(rawData.series, function(i, node) {
chartData.push({ 'name': node.name, 'y': node.data[0] })
});
And then:
series: [{
data: chartData
}]
Updated fiddle:
http://jsfiddle.net/jlbriggs/13rexxyo/5/
Output:

Related

I am trying to read an array coming from python(database mongodb), and read it in a context menu submenu

So, I am trying to read the array coming from python and python is calling mongodb. As I am trying to read the array, I am getting each character from the array. Like the code is reading the array as a string.
I have tried reading this code in various ways but always getting stuck. First, I am reading the value and putting it in a const variable. Then I am creating a for loop to loop through the array and display each item like '1 - client 1'...
var displayClient = [];
const clients = document.getElementById("clients").value;
var clients_array = clients;
console.log(clients);
var itemDisp = [];
var arrayLength = clients_array.length;
//looping through the objects inside the object
for (var i = 0; i < arrayLength; i++) {
var client = clients_array[i].toString().split(',');
displayClient.push(client[0] + ' - ' + client[1]);
itemDisp.push({ label: displayClient[i]});
}
//calling to diplay in the context menu
return {
"AddClient" : {
label: "Add Client",
"submenu": itemDisp,
disabled: false
}
//the array which I am trying to read
[['1', 'client 1'], ['2', 'client 2']]
the expected result is, to display something like; 1 - client 1... While the actual result is; [ - undefined, [ - undefined, ' - undefined...
try this:
return {
"AddClient" : {
label: "Add Client",
"submenu": itemDisp,
disabled: false
}
}
I make this and work:
var displayClient = [];
const clients = [['1', 'client 1'], ['2', 'client 2']];
var clients_array = clients;
console.log(clients);
var itemDisp = [];
var arrayLength = clients_array.length;
//looping through the objects inside the object
for (var i = 0; i < arrayLength; i++) {
var client = clients_array[i].toString().split(',');
displayClient.push(client[0] + ' - ' + client[1]);
itemDisp.push({ label: displayClient[i]});
}
//calling to diplay in the context menu
let test = {
"AddClient" : {
label: "Add Client",
"submenu": itemDisp,
disabled: false
}
}
console.log(test);
console.log(itemDisp);
I am not able to understand your code but I might understood your problem. This code can help you get the desired output :-
`
var itemDisp = [];
const clients = document.getElementById("clients").value;
try{
// This line will parse your array string into JS array object
var clientsArray = JSON.parse(clients.replace(/'/g,"\""));
for(var internalArray of clientsArray){
itemDisp.push({label : internalArray.join(" - ")});
}
}catch(e){
console.error("String provided is not a valid array string");
}
console.log(itemDisp);
`

Issue with javascript array variables

I am using javascript in my app which is a rhino javascript engine. I like to use array for an array.
The following code is my actual working code.
while (input.hasNext()) {
var data = input.next();
var new_data = {};
var i = 0;
while(i<data.get('total_entries')){
new_data.entries = data.get('total_entries');
new_data.id = data.get('out').get(i).get('id');
output.write(new_data);
i++;
}
}
I need to create array for new_data[].
while (input.hasNext()) {
var data = input.next();
var new_data[] = {};
var i = 0;
while(i<data.get('total_entries')){
new_data[i].entries = data.get('total_entries');
new_data[i].id = data.get('out').get(i).get('id');
output.write(new_data[i]);
i++;
}
}
But its not working. So, help me to create array variable in it.
Thanks.
You mean something like this:
while (input.hasNext()) {
var data = input.next();
var new_data = [];
var i = 0;
while(i<data.get('total_entries')){
new_data.push({entries: data.get('total_entries'), id: data.get('out').get(i).get('id')});
output.write(new_data[i]);
i++;
}
}
var new_data[] = {};
First of all, that's invalid JavaScript.
new_data[i]
Looks like you want new_data to be an array of objects. Why not declare it as one and add objects on every iteration of the while loop:
var new_data = [];
while(...){
new_data.push({
entries: ...
id: ...
});
}

How to convert JSON data to Array in JQuery?

I am getting Json data from result as following,
var chartData1 = [
{\"Action\":\"Twitter\",\"value\":\"1.00\",\"platform\":\"2\"},
{\"Action\":\"WhatsApp\",\"value\":\"1.00\",\"platform\":\"3\"},
{\"Action\":\"Messaging\",\"value\":\"1.00\",\"platform\":\"4\"}
]
I want to convert it to following,
var chartData2 = [
['Action', 'value', 'platform'],
['Twitter', '1.00', 2],
['WhatsApp', '1.00', 3],
['Messaging', 'WhatsApp', 4],
]
I have used different methods like parseJSON,map,etc , but i could not get expected results.
Can you help me out from this.
I'm assuming you first need to parse valid JSON string containing your data and then convert each row with object to array. And prepend whole array with array with column names. Following code will exactly do that:
var chartDataString = "[{\"Action\":\"Twitter\",\"value\":\"1.00\",\"platform\":\"2\"},{\"Action\":\"WhatsApp\",\"value\":\"1.00\",\"platform\":\"3\"},{\"Action\":\"Messaging\",\"value\":\"1.00\",\"platform\":\"4\"}]";
var chartData = JSON.parse(chartDataString);
var keys = [];
var data = [];
var row;
for (var i = 0; i < chartData.length; i++) {
row = [];
for (var key in chartData[i]) {
if (i === 0) {
keys.push(key);
}
row.push(chartData[i][key]);
}
if (i === 0) {
data.push(keys);
}
data.push(row);
}
console.log(data);
The following will convert it to an array, providing that it is already parsed as an object.
var chartData2 = Object.keys(chartData1).map(function(k) { return chartData1[k] });
console.log(chartData2);
Probably the most ideal here is to map original array to new structure:
var chartData1 = [
{"Action":"Twitter","value":"1.00","platform":"2"},
{"Action":"WhatsApp","value":"1.00","platform":"3"},
{"Action":"Messaging","value":"1.00","platform":"4"}
];
var result = chartData1.map(function(el) {
return [el.Action, el.value, el.platform];
});
result.unshift(['Action', 'value', 'platform']);
alert(JSON.stringify(result, null, 4));

JavaScript for loop returns last item in array only

I have the following function below with two for loops looping through a JSON file. The problem that I am having is in the second loop that is called in the barFactory function it is returning only the last item in the array. How do I resolve this has I am calling the chart object to create on each iteration so it shouldn't be happening according to my logic.
var looper = function(sec0, vz, lOrR) {
$('#' + lOrR + 'Title').text(sec0);
for (var i = 0; i < vz[0]['Areas'].length; i++) {
var tText = Object.keys(vz[0]['Areas'][i]);
var root = vz[0]['Areas'][i][tText][0];
barFactory(root, sec0, lOrR, i, tText);
}
function barFactory(sec1, sec0, lOrR, i, tText) {
var dataName;
for (var j = 0; j < sec1[sec0].length; j++) {
charts.title.text = sec1[sec0][j]["Label"];
dataName = sec1[sec0][j]['Metrics'][5]['Rep Res. %'].slice(0, -1);
charts.series[0].name = dataName;
charts.series[0].data = [parseFloat(dataName)];
chart = new Highcharts.Chart(charts);
}
}
}
A couple of things:
- as Barbara said, we don't see that you are changing renderTo parameter
- you are using the same object for chart creating which may cause some errors
What I suggest to do:
var dataName = dataName = sec1[sec0][j]['Metrics'][5]['Rep Res. %'].slice(0, -1);
chart = new Highcharts.Chart(
Highcharts.merge(charts, {
chart: {
renderTo: new_container_variable
},
title: {
text: sec1[sec0][j]["Label"]
},
series: [{
data: [parseFloat(dataName)],
name: dataName
}]
})
);
Also, aer you sure that: dataName = sec1[sec0][j]['Metrics'][5]['Rep Res. %'].slice(0, -1); - path after sec1 is proper one? Try to console.log(dataName); to make sure that you are passing proper value, and Highcharts makes something wrong..

Setting up a variable length two-dimensional array

I have a string as follows :
Panther^Pink,Green,Yellow|Dog^Hot,Top
This string means I have 2 main blocks(separated by a '|') :
"Panther" and "Dog"
Under these two main blocks, I have, lets say "subcategories".
I wanted to create a 2-dimensional array represented (in logic) as follows :
Panther(Array 1) => Pink(Element 1),Green(Element 2), Yellow(Element 3)
Dog(Array 2) => Hot(Element 1), Top(Element 2)
Also,I want to be able to add a main block, lets say "Cat" with possible categories "Cute,Proud" to the two dimensional array
I've managed to get an Array containing "Panther^Pink,Green,Yellow" and "Dog^Hot,Top" by using JavaScript's split function.
Note that this string is received via Ajax and can be of any length, though the format shown above is always used.
----------------------------- EDIT ----------------------------
Ok, my script so far is :
$(document).ready(function(){
appFunc.setNoOfAppBlock('Panther^Pink,Green,Yellow|Dog^Hot,Top');
appFunc.alertPing();
});
var appFunc = (function(stringWithSeper) {
var result = {},
i,
categories = new Array(),
subcategories;
return {
setNoOfAppBlock: function(stringWithSeper){
categories = stringWithSeper.split("|");
for (i = 0; i < categories.length; i++) {
subcategories = categories[i].split("^");
result[subcategories[0]] = subcategories[1].split(",");
}
},
alertPing: function(){
alert(result["Panther"][1]);
}
};
})();
However, the function "alertPing" isn't "alerting" anything.What am am I doing wrong ?
To me the most logical representation of your data:
Panther^Pink,Green,Yellow|Dog^Hot,Top
Is with a JavaScript object with a property for each category, each of which is an array with the subcategories:
var data = {
Panther : ["Pink", "Green", "Yellow"],
Dog : ["Hot", "Top"]
}
You would then access that by saying, e.g., data["Dog"][1] (gives "Top").
If that format is acceptable to you then you could parse it as follows:
function parseData(data) {
var result = {},
i,
categories = data.split("|"),
subcategories;
for (i = 0; i < categories.length; i++) {
subcategories = categories[i].split("^");
result[subcategories[0]] = subcategories[1].split(",");
}
return result;
}
var str = "Panther^Pink,Green,Yellow|Dog^Hot,Top";
var data = parseData(str);
Assuming you're trying to parse your data into something like this:
var result = {
Panther: ["Pink", "Green", "Yellow"],
Dog: ["Hot", "Top"]
}
you can use string.split() to break up your string into subarrays:
var str = "Panther^Pink,Green,Yellow|Dog^Hot,Top";
var result = {}, temp;
var blocks = str.split("|");
for (var i = 0; i < blocks.length; i++) {
temp = blocks[i].split("^");
result[temp[0]] = temp[1].split(",");
}
Data can then be added to that data structure like this:
result["Cat"] = ["Cute", "Proud"];
Data can be read from that data structure like this:
var dogItems = result["Dog"]; // gives you an array ["Hot", "Top"]
You can use something like:
function parseInput(_input) {
var output = [];
var parts = _input.split('|');
var part;
for(var i=0; i<parts.length; i++) {
part = parts[i].split('^');
output[part[0]] = part[1].split(',');
}
return output;
}
Calling parseInput('Panther^Pink,Green,Yellow|Dog^Hot,Top'); will return:
output [
"Panther" => [ "Pink", "Green", "Yellow" ],
"Dog" => [ "Hot", "Top" ]
]
To add another item to the list, you can use:
output["Cat"] = ["Cute", "Proud"];

Categories

Resources