I'm new to javascript, and I'm having trouble figuring out how to loop through some code so that it will basically create an array that I can then pass on to my plot variable.
I'm not really sure where to start. Right now I have a chunk of code that takes my first dataset (dataOne) and formats it so that it can go into my plot variable. I basically need to do that three more times for the other data sets - hoping to include the example.getDataSets function to loop through somehow.
Is there a good way to do this?
Here is my code:
script.js
var example = {};
example.data = {
dataOne: {data: [{"date":1333238400000,"data":23},{"date":1333324800000,"data":37},{"date":1333411200000,"data":49},{"date":1333497600000,"data":54},{"date":1333584000000,"data":30},{"date":1333670400000,"data":19},{"date":1333756800000,"data":15},{"date":1333843200000,"data":19},{"date":1333929600000,"data":145}],
dataTwo: {data: [{"date":1335830400000,"data":63},{"date":1335916800000,"data":77},{"date":1336003200000,"data":66}],
dataThree: {data: [{"date":1341100800000,"data":24},{"date":1341187200000,"data":50},{"date":1341273600000,"data":43},{"date":1341360000000,"data":39},{"date":1341446400000,"data":56},{"date":1341532800000,"data":66}],
dataFour: {data: [{"date":1333238400000,"data":71},{"date":1333324800000,"data":46},{"date":1333411200000,"data":66},{"date":1333497600000,"data":73},{"date":1333584000000,"data":105},{"date":1333670400000,"data":84}]}
}
example.getDataSets = function(){
return ['dataOne', 'dataTwo', 'dataThree', 'dataFour']
}
example.getSeries = function(month){
return example.data[month]
}
example.processData = function(data){
var newData = []
for(var i = 0; i < data.length; i++){
newData.push([data[i].date, data[i].data])
};
return newData;
}
My script in the HTML page:
$.getScript("script.js")
.done(function() {
var b = example.getSeries('dataOne');
var d = example.processData(b.data);
// first correct the timestamps - they are recorded as the daily
// midnights in UTC+0100, but Flot always displays dates in UTC
// so we have to add one hour to hit the midnights in the plot
for (var i = 0; i < d.length; ++i)
d[i][0] += 60 * 60 * 1000;
var plot = $.plot($("#placeholder"), [d] , options);
Any suggestions are much appreciated!
You're passing the string literal 'b' to example.processData not the object stored in the variable b. Its should be
var d = example.processData(b);
Also example.getSeries returns an object not an array. The array is in the data property of the object.
Also your data has syntax errors in it, missing ]} at the end of the arrays in the first 3 objects.
Try
var d = example.processData(b);
as
console.log('b')
won't log your data (in the b variable) as well, but the string :-)
Related
I'm tring to convert a JSON object value to an integer and calculate.
It shows representativeRow.DTA_VAL well but the value of total shows NaN.
I don't think this works because the other code works well.
datav= Number(representativeRow.DTA_VAL);
this is my code
var rows = resp.Sttsapitbldata[1].row;
if (rows) {
var representativeRow;
for (i = 1; i < 30; i++) {
representativeRow = rows[i];
if(representativeRow.ITM_NM.substring(0,2)=="부산"){
// console.log(representativeRow.ITM_NM);
var sub =representativeRow.ITM_NM.substring(0,3);
var total;
var datav;
console.log(representativeRow.DTA_VAL);
datav= Number(representativeRow.DTA_VAL);
total+=datav;
console.log(total);
}
itemNm2 = representativeRow.ITM_NM;
dataV = representativeRow.DTA_VAL;
//console.log(itemNm2);
//console.log(dataV);
options.data.data.push({locname: itemNm2, listshrs: dataV});
}
korea = webponent.visual.korea.init($(".korea"), style, options);
}
See JSON file code below.
{"Sttsapitbldata":[{"head":[{"list_total_count":88},{"RESULT":{"CODE":"INFO-000","MESSAGE":"정상 처리되었습니다."}}]},{"row":[{"STATBL_ID":"T183673021266818","DTACYCLE_CD":"YY","WRTTIME_IDTFR_ID":"2016","ITM_ID":10001,"ITM_NM":"계","CLS_ID":50033,"CLS_NM":"강간","UI_NM":"명","DTA_VAL":5155,"DTA_SVAL":null},{"STATBL_ID":"T183673021266818","DTACYCLE_CD":"YY","WRTTIME_IDTFR_ID":"2016","ITM_ID":10002,"ITM_NM":"서울","CLS_ID":50033,"CLS_NM":"강간","UI_NM":"명","DTA_VAL":1129,"DTA_SVAL":null},{"STATBL_ID":"T183673021266818","DTACYCLE_CD":"YY","WRTTIME_IDTFR_ID":"2016","ITM_ID":10003,"ITM_NM":"부산","CLS_ID":50033,"CLS_NM":"강간","UI_NM":"명","DTA_VAL":314,"DTA_SVAL":null},
You should initialise total=0. You can't add to a null value on the first iteration. Although looking at it, I suspect you'd be wanting to initialise total outside of the loop
I have a problem adding the object "myobj" to the arrays data / data2. As you see "myobj" a JS object which I would like to add to either data or data2. the functions are being triggered by clicks on different buttons.
console.log of myobj shows me
{ array: "arr_id_1", axis: "x", acc: "", vel: "", dist: "", jerk: "" }
I receive an error saying data2.splice() is not a function.
which is the format I need. "myobj" is supposed to be added to an array which I want to use JSON.stringify on. This JSON literal goes then to a python script via ajax. The array "data" is being filled with each click I perform correctly but not in the format for further processing. So I tried to fill array data2 since I have read that I could use .splice() as well. Unfortunately, console.log(data2) shows "undefined" for each field I try to fill and I have no idea how to solve it.
I tried to use JSON.stringify on "myobj" and as another attempt, I have tried to JSON.parse it back again. I tried adding the brackets and colons into quotes but no success either.
I am grateful for any advice or help.
var counterx = 0;
let data = [];
let data2 = {};
function valuesX() {
counterx++;
// does something here
let arr_id = [];
arr_id.name = 'arr_id_' + counterx;
let ind = counterx - 1;
let myobj;
function arr() {
var ind = sel.selectedIndex;
var axis = sel.options[ind].text;
arr_id.length = 0;
arr_id.push(arr_id.name, axis, btna.value, btnv.value, btns.value, btnj.value)
myobj = {
array: arr_id[0],
axis: arr_id[1],
acc: arr_id[2],
vel: arr_id[3],
dist: arr_id[4],
jerk: arr_id[5]
};
console.log(arr_id.name, arr_id)
console.log(myobj)
console.log(data.name, data)
console.log(data2.name, data2)
}
data.name = 'data';
data2.name = 'data2';
data.splice(ind, 0, arr_id)
data2.splice(ind, 0, myobj)
}
SOLUTION:
I have converted the myobj to an object using Answer from JVE999, first suggestion and used .splice() to add the every new myobj to the array data. I have used splice because I need to overwrite already existing elements while keeping the order (Thus the indx) when I trigger the function (.splice() reference).
var arr_id = [];
arr_id.name = 'arr_id_'+counterx;
var myobj;
var indx = counterx-1;
var data_new;
data.name = 'data';
function arr(){
var ind = sel.selectedIndex;
var axis = sel.options[ind].text;
arr_id.length = 0;
arr_id.push(arr_id.name, axis, btna.value, btnv.value,btns.value, btnj.value)
myobj = {
array:arr_id[0],
axis:arr_id[1],
acc:arr_id[2],
vel:arr_id[3],
dist:arr_id[4],
jerk:arr_id[5]
};
data_new = convArrToObj(myobj);
data.splice(indx, 1, data_new)
data_str = JSON.stringify(data)
console.log(data.name, data)
console.log(data_str)
}
I'm having trouble organizing this data the way I would like it to. On my pages, a few things happen that I know work...
Some PHP spits out a multidimensional associative array. The top level of this array is an array of regions. Each region is an array of timezones.
Some more PHP creates a second multidimensional associative array. The top level of this array is an array of regions. Each region is an array of UTC offsets.
Both arrays are generated in the same order from the same data. This means that $offsets["region"][0] will have be based on the same timezone as $timezones["region"][0].
Both arrays are encoded into JSON and passed to my JavaScript.
I have the following JavaScript code...
var tempCurrentTimezoneArray = timezoneArray[ $("select[name='region_selector']").val() ];
var tempCurrentOffsetArray = timezoneOffsetArray[ $("select[name='region_selector']").val() ];
var groupedTimezones = {};
var groupedOffsets = {};
for (counter = 0; counter < tempCurrentOffsetArray.length; counter++) {
significantOffset = tempCurrentOffsetArray[counter].substr(tempCurrentOffsetArray[counter].length - 2);
if (!(significantOffset in groupedTimezones)) {
groupedTimezones[significantOffset] = [];
groupedOffsets[significantOffset] = [];
}
groupedTimezones[significantOffset].push(tempCurrentTimezoneArray[counter]);
groupedOffsets[significantOffset].push(tempCurrentOffsetArray[counter]);
}
var offsetArray = [];
for (var property in groupedTimezones) {
if (!groupedTimezones.hasOwnProperty(property)) {
continue;
}
groupedTimezones[property].sort();
groupedOffsets[property].sort();
offsetArray.push(parseInt(property));
}
offsetArray.sort();
var currentTimezoneArray = [];
var currentOffsetArray = [];
for (counter = 0; counter < offsetArray.length; counter++) {
currentTimezoneArray = currentTimezoneArray.concat(groupedTimezones[offsetArray[counter]]);
currentOffsetArray = currentOffsetArray.concat(groupedOffsets[offsetArray[counter]]);
}
In the top two lines I remove all of the timezone data not pertaining to the region selected on the page. This means that I am left with 2 single-dimensional arrays. Any given index of either array relates directly to the other array. I.E....
tempCurrentOffsetArray[0] is the UTC offset of the timezone found at tempCurrentTimezoneArray[0].
The rest of this code is intended to complete the following tasks...
Group timezones and offsets by their UTC offset.
Organize each offset group in alphabetical order.
Create two arrays where values are organized first by UTC offset and second by alphabetical order.
The problem I'm having is that on some regions I receive almost perfect listings,and on others I receive some listings with a seemingly random number of undefined values, and I'm not sure why. Can anyone identify the syntactical or logical errors in my code?
JSON of tempCurrentTimezoneArray input data here
JSON of tempCurrentOffsetArray input data here
You think still too complicated. It is a mess to keep these two Arrays in sync, better use one Array with objects.
var region_selector = $("select[name='region_selector']").val();
var tempCurrentTimezoneArray = timezoneArray[ region_selector ];
var tempCurrentOffsetArray = timezoneOffsetArray[ region_selector ];
//consolidate the Arrays
var data = []; //create a new Array `data`
for(var i = tempCurrentOffsetArray.length; i--; ){
//write into Array `data` at index `i` an object, containing these properties:
//`timezone`, `offset` and `offsetValue`, and their respective values
data[i] = {
timezone: tempCurrentTimezoneArray[i],
offset: tempCurrentOffsetArray[i],
//the + at the beginning converts the value behind that into a Number, like parseFloat() would do
offsetValue: +tempCurrentOffsetArray[i].match(/^GMT([+-]\d+(?:\.\d+)?)$/)[1]
}
}
//sorter-function for data to sort the values by offsetValue ASC first, then by timezone ASC
function sortedByOffset(a, b){
return a.offsetValue - b.offsetValue || a.timezone.localeCompare(b.timezone);
}
//you should do this as late as possible, usually after the filtering
data.sort(sortedByOffset);
If you insist on the two output-Arrays
var currentTimezoneArray = data.map(d => d.timezone);
var currentOffsetArray = data.map(d => d.offset);
otherwise this is imo more flexible
//utilities to fetch a property off the object
var getTimezone = d => d.timezone;
//aka function getTimezone(d){ return d.timezone }
var getOffset = d => d.offset;
//aka function getOffset(d){ return d.offset }
//example usages:
data.filter(d => d.offset === "GMT-5").map( getTimezone );
data.filter(d => d.offsetValue >= -2 && d.offsetValue <= -5 ).map( getOffset );
taking the first example; thinking in terms of a SQL-statement this would be
SELECT timezone FROM data WHERE offset = "GMT-5"
get me the timezone-values for each entry where the offset is GMT-5
you start with an Array containsing all values data then you get the subset you are interested in (in this case every entry, with the offset "GMT-5") by filtering.
Now you have an Array containing all values you are intersted in, but still the whole objects; like a SELECT * FROM ...
the map() function calls the function getTimezone() on every entry in this subset and returns another Array containing only the timezone-values.
The second example defines a range for the filter (every entry from GMT-2 to and including GMT-5 and every GMT in between) and returns for these entries the offset-protperty.
I discovered the issue with my code. There were actually three issues the first being on line 6. After looking over the data one more time I realized that some of the values had offsets that were floating point integers or had more than two significant digits. The new line 6 is...
significantOffset = tempCurrentOffsetArray[counter].replace(/[^\d.-]/g, '');
The second issue with my code also had to do with parsing floating integers. On line 21 we need to use parseFloat instead of parseInt. The new line 21 is...
offsetArray.push(parseFloat(property));
The third issue lies on line 23. sort() needs to be told how to sort the integers. This is the new line 23...
offsetArray.sort(function(a, b){return a-b});
The final code looks like this...
var tempCurrentTimezoneArray = timezoneArray[ $("select[name='region_selector']").val() ];
var tempCurrentOffsetArray = timezoneOffsetArray[ $("select[name='region_selector']").val() ];
var groupedTimezones = {};
var groupedOffsets = {};
for (counter = 0; counter < tempCurrentOffsetArray.length; counter++) {
significantOffset = tempCurrentOffsetArray[counter].replace(/[^\d.-]/g, '');
if (!(significantOffset in groupedTimezones)) {
groupedTimezones[significantOffset] = [];
groupedOffsets[significantOffset] = [];
}
groupedTimezones[significantOffset].push(tempCurrentTimezoneArray[counter]);
groupedOffsets[significantOffset].push(tempCurrentOffsetArray[counter]);
}
var offsetArray = [];
for (var property in groupedTimezones) {
if (!groupedTimezones.hasOwnProperty(property)) {
continue;
}
groupedTimezones[property].sort();
groupedOffsets[property].sort();
offsetArray.push(parseFloat(property));
}
offsetArray.sort(function(a, b){return a-b});
var currentTimezoneArray = [];
var currentOffsetArray = [];
for (counter = 0; counter < offsetArray.length; counter++) {
currentTimezoneArray = currentTimezoneArray.concat(groupedTimezones[offsetArray[counter]]);
currentOffsetArray = currentOffsetArray.concat(groupedOffsets[offsetArray[counter]]);
}
Basically what i'm doing, is trying to create my own steam market JSON, by HTML parsing.
Example of how I'm currently doing that :
var url = 'http://steamcommunity.com/market/search?appid=730'
var itemDiv = $("<div></div>")
$.get(url).success(function(r){
data = $(r).find('stuff i need')
itemDiv.append(data)
})
and now say I wanted to find names of the items in the div, i would do something like :
itemDiv.find('x').each(function(){
var name = $(this).find("y").text()
// console.log(name) [or do whatever is needed ect]
})
As I mentioned before, I need to return objects based on that data in the format of:
var item = {name:"",price:0}
However, things like price will always be changing.
Based on the data thats in the div, the final product would look along the lines of :
var x = {name:"a",price:1}
var x2 = {name:"a2",price:2}
How do I go about doing this? I thought maybe i could store the data in an array, and then do something like
for(x in y){
return object
}
or something along those lines.
Sorry if this seems like a bonehead question, I'm pretty new to javascript.
clarification: i'm trying to figure out how to return multiple objects based on the data inside the div.
Here is the code that builds an array of objects based on two arrays (assuming they are of equal length).
function buildStocks() {
// Names and prices can also be passed as function arguments
var names = ['a', 'b', 'c'];
var prices = [1, 2, 3];
var result = []; // Array of these objects
for (var i = 0; i < names.length; i++) {
result.push({
name: names[i],
price: prices[i]
});
}
return result;
}
I'm new to javascript, and I'm having trouble figuring out how to loop through some code so that it will basically create an array that I can then pass on to my plot variable.
I'm not really sure where to start. Right now I have a chunk of code that takes my first dataset (dataOne) and formats it so that it can go into my plot variable. I basically need to do that three more times for the other data sets - hoping to include the example.getDataSets function to loop through somehow.
Is there a good way to do this?
Here is my code:
script.js
var example = {};
example.data = {
dataOne: {data: [{"date":1333238400000,"data":23},{"date":1333324800000,"data":37},{"date":1333411200000,"data":49},{"date":1333497600000,"data":54},{"date":1333584000000,"data":30},{"date":1333670400000,"data":19},{"date":1333756800000,"data":15},{"date":1333843200000,"data":19},{"date":1333929600000,"data":145}]},
dataTwo: {data: [{"date":1335830400000,"data":63},{"date":1335916800000,"data":77},{"date":1336003200000,"data":66}]},
dataThree: {data: [{"date":1341100800000,"data":24},{"date":1341187200000,"data":50},{"date":1341273600000,"data":43},{"date":1341360000000,"data":39},{"date":1341446400000,"data":56},{"date":1341532800000,"data":66}]},
dataFour: {data: [{"date":1333238400000,"data":71},{"date":1333324800000,"data":46},{"date":1333411200000,"data":66},{"date":1333497600000,"data":73},{"date":1333584000000,"data":105},{"date":1333670400000,"data":84}]}
}
example.getDataSets = function(){
return ['dataOne', 'dataTwo', 'dataThree', 'dataFour']
}
example.getSeries = function(month){
return example.data[month]
}
example.processData = function(data){
var newData = []
for(var i = 0; i < data.length; i++){
newData.push([data[i].date, data[i].data])
};
return newData;
}
My script in the HTML page:
$.getScript("script.js")
.done(function() {
var b = example.getSeries('dataOne');
var d = example.processData(b.data);
// first correct the timestamps - they are recorded as the daily
// midnights in UTC+0100, but Flot always displays dates in UTC
// so we have to add one hour to hit the midnights in the plot
for (var i = 0; i < d.length; ++i)
d[i][0] += 60 * 60 * 1000;
var plot = $.plot($("#placeholder"), [d] , options);
Any suggestions are much appreciated!
Loop over the value returned from .getDataSets, too
var sets = example.getDataSets(), set_i = 0, // get list of sets
b = {}, d = [], i = 0, plot; // set-up vars
for(; set_i < sets.length; set_i++){ // loop over each set
b = example.getSeries( sets[ set_i ] ); // get your set
d = example.processData(b.data);
for (i = 0; i < d.length; ++i)
d[i][0] += 60 * 60 * 1000;
plot = $.plot($("#placeholder"), [d] , options);
// ... etc with plot
}
If you want them all in one array before plotting, use concat on another array (call it d_total or something) and then in the set loop, d_total = d_total.concat( d );, then plot outside loop
I'm assuming you want to process each of
var b = example.getSeries(X);
where X is, in turn, 'dataOne', 'dataTwo', 'dataThree', 'dataFour'?
If so, you'll be looking for something like this:
// see below for where example.ordering is suggested
for (var i in example.ordered) {
var month = example.ordered[i];
var b = example.getSeries(month);
var d = example.processData(b.data);
... further processing with month, b, d.
}
The getDataSets() is fine for yielding your 'months' in what must be proper order for you. My only concern is that you have the list of months in two places. The array you have is necessary for ordering the months, because you cannot extract the 'month names' from example.data and expect them to be in the same order (keys are essentially stored randomly due to hashing).
The qualification would be if your keys are sortable, but the keys you have here are not. Of course, if you're building the pair of structures from the same source, then storing the data in the associated array (example.data object) along with a separate array to indicate ordering is both common and acceptable. Ideally you'd pair these two into yet another object so they can be handled as a team.
Since your array of ordered months is literally 'lost' in a function, I would suggest you add something like
example.ordering = [ ..... ]
and even better, push the months onto the end of that list in the same order they are put into the hash. I would be using a helper function to store the data:
example.ordering = []; // initially empty
example.storeSet = function (month, dataList) {
example.ordering.push(month);
example.data[month] = { data : dataList };
}
....
// now store the data
example.storeSet('dataOne', [{"date":1333238400000,"data":23}, ....]);
example.storeSet('dataTwo', [{"date":1335830400000,"data":63}, ....]);
example.storeSet('dataThree', [{"date":1341100800000,"data":24}, ....]);
example.storeSet('dataFour', [{"date":1333238400000,"data":71}, ....]);
Of course my code is untested (of course!) but it looks right, and I'm sure you can fix any stupid mistakes I might have made.
I am new and understand your frustration when you have sat and looked and still cannot find the answer. However, what I think you are looking for is something like this:
for (example.data=dataOne;example.data<dataFour;example.data=example.data+increment)
{
code to be executed
}
or maybe even recursively but I am not the best at that but below is an standard example
function recurs(p1) {
p1--;
if (p1 < 0) return // exit condition
setTimeout("recurs("+p1+")",1);
}