I am reading a value from a dropdown list depending on what option is selected. I am using jqPlot to graph the values.
jqPlot expects an array of values like [91, 6, 2, 57, 29, 40, 95]
but when I read the value in from the dropdown box it is coming in as a whole string "[91, 6, 2, 57, 29, 40, 95]"
I tried splitting it but I got ["91", "6", "2", "57", "29", "40", "95"] which wont display the graph correctly.
Is there anybody that has encountered something like this before and what can I do to make my values convert into a number array.
Thanks for any help
You can use JSON.parse() to convert that string into a JavaScript array. The numbers in the string are not quoted so the array will also contain numbers. And you can delete all the code that parses the string as you won't need it anymore.
>>> JSON.parse("[91, 6, 2, 57, 29, 40, 95]")
[91, 6, 2, 57, 29, 40, 95]
If you need to support legacy browsers, add json2.js to shim JSON support in browsers not supporting it natively.
You can use JSON.parse to change the string "[91, 6, 2, 57, 29, 40, 95]" into an array:
(function(){
var a = '[1,2,3]';
var b = JSON.parse('[1,2,3]');
alert(b +'\n'+ typeof(b)+'\n'+ b[0] );
})()
Demo
As you are using jQuery you can do
$.parseJSON("[91, 6, 2, 57, 29, 40, 95]");
you can use
str.slice(1, -1).split(',').map(function(s){return parseInt(s, 10);});
Related
Could someone please help me sort object by key with given array?
given array ['NAME',20200229,20200131,20200331]
given object {20200131: 51, 20200229: 50, 20200331: 170, NAME: "a"}
Object.fromEntries was expected to build object in the given keys
Object.fromEntries(Object.entries({b: 3, a:8, c:1}))
//{b: 3, a: 8, c: 1} <-- works fine
But when I try with keys that has number and alphanumerics it's doesn't work
let sortingArr = ['NAME',20200229,20200131,20200331] // desired sort, for example
// All below gives the same result
Object.fromEntries(Object.entries({NAME: 'a',20200131: 51, 20200229: 50, 20200331: 170}))
// sort asc naturally,.. ok
Object.fromEntries(Object.entries({NAME: 'a',20200131: 51, 20200229: 50, 20200331: 170}).sort())
// sort asc naturally,.. redundant... ok, no problems
Object.fromEntries(Object.entries({NAME: 'a',20200131: 51, 20200229: 50, 20200331: 170}).sort((a, b)=> parseInt(a)||0 + sortingArr.indexOf(b)))
//Problem! was supose to consider the sorting logic*, right?
//*Sorting works: Object.entries({NAME: 'a',20200131: 51, 20200229: 50, 20200331: 170}).sort((a, b)=> parseInt(a)||0 + sortingArr.indexOf(b))
//0: ["NAME", "a"]
//1: ["20200131", 51]
//2: ["20200229", 50]
//3: ["20200331", 170]
I read other responses and they are very redundant, with people wanting only in ascending (or descending) order, without the desired array
I have this array of Object that I am getting from my database:
[Array of Object][1]
I would like to make an array of array for each value, but I can't manage to find a way to do it as I'm a beginner of javascript.
For example :
var Stats=[
[39,49,43,42,41,35], //SGW Value for each Object
[37,44,49,46,52,42], //UD Value for each Object
[8,11,8,8,16,15], //Virtual Value for each Object
...
]
The goal is to make a chart on chart.js that look like that :
[Chart Goal][2]
I would need to loop the dataset because I'll add more data and it would be way too long to set each dataset individually.
Thanks for your time.
You can do it like this:
let array1 = [
{
param1: 10,
param2: 20
},
{
param1: 30,
param2: 40
}
]
let array2 = array1.map(item => Object.values(item));
console.log(array2); // prints [[10, 20], [30, 40]]
First of all you need to create an array for each property you want to plot; i.e.:
var fsp = [],
msg = [],
sgw = [];
Then you can loop over your dataset and put the data in each array:
yourArray.forEach(function(obj){
//obj takes the value of each object in the database
fsp.push(obj.fsp);
msg.push(obj.msg);
sgw.push(obj.sgw);
})
or, if you are more familiar with for loop
for(var obj of yourArray){
fsp.push(obj.fsp);
msg.push(obj.msg);
sgw.push(obj.sgw);
}
Finally you can create an array as you pointed in your example
var result = [];
result.push(fsp, msg, sgw);
And the result will be
[
[89, 59, 43, 60, 81, 34, 28, 58, 75, 41],
[77, 91, 4, 56, 6, 1, 42, 82, 97, 18],
[24, 34, 4, 13, 75, 34, 14, 41, 20, 38]
]
For more informations take a look at Array.forEach(), Array.push() and for...of documentations
EDIT
As you pointed in your comment, you can generate arrays dynamically creating an object like var arrays = {};. Then in forEach(), or if for...of, you need to loop over objects with a for...in loop. The variable you declare in loop's head takes the value of index, numeric for Arrays, literal for Objects. You have to do something like:
yourArray.forEach(function(obj){
for(let index in obj){
if(!arrays[index]) // check if property has already been set and initialized
arrays[index] = []; // if not, it's initialized
arrays[index].push(obj[index]) // push the value into the array
}
})
Note that Object has been treated as Array because you access its properties with a variable filled at runtime.
The result will be:
arrays = {
fsp: [89, 59, 43, 60, 81, 34, 28, 58, 75, 41],
msg: [77, 91, 4, 56, 6, 1, 42, 82, 97, 18],
sgw: [24, 34, 4, 13, 75, 34, 14, 41, 20, 38]
}
To obtain only arrays use Object.values().
If you cannot imagine how this works, I suggest you to make some examples in Chrome Developer Tools' console, or in Node's console, or wherever you can have a realtime feedback, putting in the middle of code some console.log() of variables
I have the following small dataset hardcoded into a variable in my code:
var dataset = [['CENTRAL', 44, 552, 18565],
['NORTHERN', 42, 945, 20092],
['SOUTHERN', 96, 795, 30095],
['PARK', 1, 640, 9341],
['MISSION', 66, 1198, 18542],
['TENDERLOIN', 23, 113, 10735],
['RICHMOND', 9, 561, 9082],
['TARAVAL', 81, 789, 11966],
['INGLESIDE', 5, 1368, 13414],
['BAYVIEW', 7, 985, 14711]];
Now, this dataset is taken directly from a .csv file, that looks like this:
District,Prostitution,VehicleTheft,Totalcrimecount
CENTRAL,44,552,18565
NORTHERN,42,945,20092
SOUTHERN,96,795,30095
PARK,1,640,9341
MISSION,66,1198,18542
TENDERLOIN,23,113,10735
RICHMOND,9,561,9082
TARAVAL,81,789,11966
INGLESIDE,5,1368,13414
BAYVIEW,7,985,14711
However, I'd obviously like to be able to just read in the file, which I've attempted using this:
var dataset_csv = d3.csv("datafile.csv", function(d){
console.log(dataset_csv = d)
});
Which gives me an array of objects that look like this:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
District: "CENTRAL"
Prostitution: "44"
Totalcrimecount: "18565"
VehicleTheft: "552"
My question is, and it might be trivial, how can I transform those objects into an array data structure like my initial dataset? I've been battling with it for some time now. Any hints greatly appreciated.
Use Array#map to iterate over each object and Object.keys to catch only the keys values.
var dataset_csv = [{District: "CENTRAL", Prostitution: "44", Totalcrimecount: "18565", VehicleTheft: "552"}, {District: "WEST", Prostitution: "22", Totalcrimecount: "4324", VehicleTheft: "53"}, {District: "EAST", Prostitution: "11", Totalcrimecount: "23434" , VehicleTheft: "76"}],
datasetArr = dataset_csv.map(v => Object.keys(v).map(c => Number(v[c]) ? Number(v[c]) : v[c]));
console.log(datasetArr);
I have a tuple (could also use list instead) like this:
(1, 'jsmith', 'Ferrari', '10 million', 39, 16, 2, 0, '-')
What would be a sensible way to represent this as a JSON struct in python? The key is a string like so:
{
"John Smith" : (1, 'jsmith', 'Ferrari', '10 million', 39, 16, 2, 0, '-')
}
Any suggestions? The JSON will be parsed in JS in the front end and will always be the same length. Missing entries are represented by '-'.
Use json.dumps.
>>> import json
>>> data = (1, 'jsmith', 'Ferrari', '10 million', 39, 16, 2, 0, '-')
>>> json.dumps({'John Smith': data})
'{"John Smith": [1, "jsmith", "Ferrari", "10 million", 39, 16, 2, 0, "-"]}'
BTW, JSON has only array ([...]); no distinction between list and tuple.
Represent a list as an array, i.e. beginning with [ and ending with ].
I'm trying to solve a problem I have with multiple javascript arrays.
So basically the result I want is to match the arrays of a dropdown box with other values from other arrays that I will display.
The arrays contain different values, but the order is the most important thing
var array1 = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22];
var array2 = [30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50];
var array3 = [36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56];
Let's say the user selects number 4, then I need to somehow select 32 in array2 and 38 in array3.
Any suggestions are gladly accepted, Thanks!
Get the index from the first array, with Array.prototype.indexOf
var index = array1.indexOf(4);
Get the values from other arrays with that index, like this
console.log(array2[index], array3[index]);
Note: If the value being searched is not found in the array, indexOf will not fail with an error but it will simply return -1. So, you might want to check before using that to access the elements from other arrays, like this
var index = array1.indexOf(4);
if (index !== -1) {
console.log(array2[index], array3[index]);
} else {
console.log("Invalid element selected");
}
Any time you have multiple parallel arrays, you should really consider refactoring it into a single array of objects. That way you never have to worry about keeping them synched. For example:
var myArray = [ { val1: 2, val2: 30, val3: 36 }, { val1: 4, val2: 32, val3: 38 }, ...];
Now to find the value for 4 you can simply do something like (although a simple for loop might be more efficient since you know there is only ever one result):
var myValues = myArray.filter(function(item) { return item.val1 === 4 });
And then access myValues[0].val2 and myValues[0].val3.
Or, if you are always looking up by the first value, you can use that as your key for an object that maps to your other two values. Something like:
var myArray = { 2: { val2: 30, val3: 36 }, 4: { val2: 32, val3: 38 },...};
Now if you want the other two values for 4 you can simply:
var value2 = myArray[4];
var value3 = myArray[4];
Assuming those are not only arrays and values, but you have actual <select> dropdown boxes:
Accessing the selected value is not only possible by using select1.value, but also by using select1.options[select1.selectedIndex].value. That.selectedIndex is what we are interested in, and you can use that equivalently on the option collections of the other two dropdowns, or the arrays with their values:
select2.options[select1.selectedIndex].value
array2[select1.selectedIndex]
select3.options[select1.selectedIndex].value
array3[select1.selectedIndex]
If you access them via the options collection you will need to make sure that one option is actually selected (select1.selectedIndex != -1), otherwise you'd get an exception.
Do it like this,
var valueFromSelect = 4;
var array1 = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22];
var array2 = [30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50];
var array3 = [36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56];
for(var i = 0; i < array1.length; i++){
if(valueFromSelect == array1[i]){
console.log(array2[i], array3[i]);
break;
}
}
I suggest you don't use indexOf, it's not compatible with IE < 9 read more about that here indexOf MDN