Building an array in Javascript for loop - javascript

Well, turns out camp_amount wasn't setup properly and returned "NaN"... Thanks anyway! You guys made me look past the array syntax, which turns out to be fine. Sometimes I just get a bit lost in code.
For use with highcharts I have the following array:
dashboardData = [[tableData[1], parseFloat(tableData[12])],[tableData[14], parseFloat(tableData[25])]];
I can literally just paste that as highcharts series data:
data: dashboardData
However, I need to build the array in a for loop because the length of the array will vary. So I need to build an array that ends up with the same structure as above, which would be something like:
0: Array[2]
0: "a string"
1: 312
1: Array[2]
0: "another string"
1: 1668
How do I build this up? I tried the following but it doesn't work...
var dashboardData = [];
for (var i = 1; i <= camp_amount.length; i++) {
dashboardData.push([tableData[i], tableData[i + 1]]);
}

Related

Confusion on getting Javascript to see a lsit of lists from Python via JSON as such

I am working on a Django app. I need to pass back a few parameters from the server, which I do with this code:
num_periods = 25
num_traces = 2
opacities = [0.5, .99]
ys = [[1,2,3,4,5],[7,6,5,4,3]]
response = {'text' : request.POST['value'],
'num_periods' : num_periods,
'num_traces' : num_traces,
'opacity': opacities,
'ys': ys
}
return JsonResponse(response)
On the client side, in the Ajax callback, I have code that looks like this:
success : function(data) {
console.log('num traces = ' + data.num_traces);
console.log('opacitiees = ' + data.opacity);
console.log('data = ' + data.ys);
but, console.log(ys) gives data = 1,2,3,4,5,7,6,5,4,3, which looks flattened.
However, if I do console.log(ys[1]), it 'looks like' an array: 7,6,5,4,3, though with no brackets. So, JS is aware of the nested list structure.
But any attempt to get it into a list of lists of numbers fails. for example this code:
z=[]
z.push(ys[0])
z.push(ys[1])
gives me back z = 1,2,3,4,5,7,6,5,4,3 when I do console.log("z = " + z)
Something deeply confusing is happening here. I also tried Object.values(ys[0]), but still this does not give a list. Other ideas I have seen are a clever use of slice like so :
var ys=[];
while(list.length) ys.push(list.splice(0,5));
console.log("ys[0]="+ys[0]);
which gives
ys[0]=1,2,3,4,5,7,6,5,4,3
How do you take the JSON that was received from Python and get it to look like the basic list of lists that I clearly need? Stuffing '[' and ']' around things before assigning does no good...
What seems very confusing is that if I do a 'loopback' within Javascript by doing something like
var foo = JSON.parse(JSON.stringify( { 'ys' : [[1,2,3],[4,5,6]]))
then things look better: the type of foo.ys is now Array[ Array[5], Array[5] ]. But the type of what I am getting with the actual Python-JS transfer is just that list of numbers, with type 'Object'.
(1) use the development tools of your browser to see what is sent back and forth between the server and the browser (F12 on all browsers).
(2) you can use commas in console.log('ys=', ys);
I'd be very surprised if it isn't in fact a list of lists with the same values you sent.
The problem is that here it (implicitly) calls toString, which you can see doesn't put any square brackets around the array. That means it doesn't put brackets around smaller arrays either - so it looks like it's flat. To make it look like the object in your code, you can convert it to JSON:
JSON.stringify([[1, 2, 3], [4, 5, 6]])
will be
"[[1,2,3],[4,5,6]]"
which you can then log or do more with. (while [[1, 2, 3], [4, 5, 6]].toString() is "1,2,3,4,5,6"). All of your actual data structures are entirely as you expected, the problem is just in the step of turning them into strings for output - so you don't need to do any more processing on the variables themselves, until you need to represent them as strings.

javascript to python array translation

We are working on a project where we are translating javaScript code into python. Everything is going pretty smoothly, except for this one line of code that has given us errors on multiple translations:
"primes" is an empty array BTW.
JavaScript:
var primes = [];
if(primes[primes.length - 1] > 3){...}
Python:
primes = []
if primes[len(primes) - 1] > 3:
......
This code works in javascript, however in Python we get an error. It seems as though we are trying to access an index of the list that doesn't exist.
This is the error:
TypeError: object of type 'int' has no len()
Does anyone have a workaround?
Python hasn't a safe get so you should change your code this way:
primes = []
if primes and primes[len(primes) - 1] > 3:
...
Even better, to get the last of the list you can use primes[-1]
primes = []
if primes and primes[-1] > 3:
...

split() is not giving the expected outcome

I'm having problems why my .split() function.
somehow when i splay my line the first [0] element in the array can be accessed but the 2nd [1] can't
I have the following string:
,{"relationID":"000001","recID":"1d2712eb-4f08-4b4f-b6e9-600c9631b503"
And the code below is how i try to split this (tempArray contains a x number of strings like the above):
var templine = tempArray[i].substr(1, tempArray[i].length);
//alert(templine);
var line = templine.split(',');
var s1 = line[0].split('"')[3];
var s2 = line[1].split('"')[3];
when i use alert(s1) or alert(s2) i do get the value however, the folowing error always occurs on the last line (var s2):
caught TypeError: Cannot read property 'split' of undefined
this causes the rest of my script to crash and it won't finish what it's supposed to, displaying an empty page.
My question, what is going wrong here? why does s1 function properly and s2 which is exactly the same except for the index of the line array crash my script.
I want to emphasise when i use the alert function to check the value of my variable s1 and s2 they do contain the right value.
EDIT:
maybe a nice bonus since there might be an easyer way.
after I've gotten the values s1 and s2 i want to put them in a map like so:
map[s2] = s1;
as you can probably tell the string i use is the result of splitting 1 humongous string on ('}'). the code displayed here is what i do when looping trough this array.
That can only be caused by a attempt to access element on the array that is really undefined. Probably your input is not what you are expecting.
Check if line.length > 1 before you try to read those indexes of the array.
As it seems to be a JSON, may be you should try to parse the JSON, it would make your code more readable and reliable. Check JSON.parse browser compatibility before using it (IE8+).
For example:
var data = JSON.parse('{ "field1": "value1", "field2": "value2" }');
var s1 = data['field1'];
var s2 = data['field2'];
Hope I've helped.

How to read json data in typeahead.js?

I want to read my data in JSON file then using it with typeahead.js here's a link
if some one write any word like EnglishWords [Best] it will show him/she list all of the words that started with best or like best and select the word then show the description of the word
but I have no any idea because I am new in javascript and json thanks a lot :)
here's example of my json data file
var Words = [
{"EnglishWords":"Best","Description":"an expression of good some this"},
{"EnglishWords":"Best wishes","Description":"an expression of hope"},
{"EnglishWords":"Application","Description":"Computing a program or piece of software"},
-
-
-
-
-
-
];
It looks like you have two separate things going on. One of is the autocomplete and the other some kind of word/phrase definition?
typeahead.js is only going to address the first part but it seems easy enough. Adapting the example from the github page, you'd want something like:
$('input.englishwords').typeahead({
name: 'words',
local: ['application', 'best', 'best wishes']
});
EDIT:
You'll have to parse your JSON object into an array or into an object that typeahead wants. Something like:
var typeList = [];
for (var i = 0; i < Words.length; i++) {
typeList.push(Words[i].EnglishWords);
}
then:
$('input.englishwords').typeahead({
name: 'words',
local: typeList
});

Javascript explode issue

I am running an ajax query and returning JSON and one of the results is a field named image.comment e.g.
test~63~Dave Sanders~http://graph.facebook.com/998433599/picture?type=large~Dave Sanders~9 minutes ago
I'm using ~ as a separator
There maybe be multiple similar sets of data separated by ---- in image.comment so to parse the data and add it to the DOM i'm using:
if(image.comment){
html += '<div class="msgs_holder'+image.list_id+'">';
// split comment at ----
var comString = image.comment;
var comArray = comString.split("----");
var lengthArray = comArray.length,
element = null;
for (var i = 0; i < lengthArray; i++) {
element = comArray[i];
// split indiv comment at ~
var comUserString = element;
var comUserArray = comUserString.split("~");
html += '<div class="msgs_row"><div class="msgs_pic"><img src="'+comUserArray[3]+'"></div>';
html += '<div class="msgs_comment"><span class="msgs_name">'+comUserArray[2]+'</span> '+comUserArray[0]+'<br><span class="msgs_time" title="'+comUserArray[5]+'">'+comUserArray[5]+'</span></div></div>';
}
html += '</div>';
}
But the page fails to load and firefox firebug tells me: allocation size overflow
This only happens on rows of the JSON where there is data in comment column
I suspect some maybe infinite looping but can't see it
I've checked the query and it runs fine so not that
Is this the best way to explode in js?
Any ideas?
MORE INFO The reason I'm doing it this way is it's a piece of a much bigger query. Images loaded to a page with comments under each image. So I'm loading the comments into a column to be parsed for display.
Example:
Image 1 Image 2 Image 3 etc etc etc
hey i think its great!
hey back! me too
I'm not sure
MORE INFO 2 This data is taken from a MySQL query e.g
select w.img_width, w.img_height, w.prod_pic_url as preview3,
GROUP_CONCAT(ww.comment,'~', h.user_id,'~', h.name,'~',
h.live_prof_pic,'~', h.twovo_url,'~', time_ago(ww.dateadded) SEPARATOR '----') AS comment
from tableName where blah=blah
GROUP_CONCAT is the comments section mentioned above
So, to use JSON for data within data, is that possible? If so how?
Example returned data:
"preview3":"http:\/\/myurl.com\/wish_images\/production\/3578.jpg","comment":"test~63~Dave Sanders~http:\/\/graph.facebook.com\/Dave Sanders\/picture?type=large~Dave Sanders~39 minutes ago"},{"item_id":"3559","numComms":"0","numLikes":"0"... etc etc
This isn't suited for a comment, so I'll try to write what I think people are saying with respect to using JSON instead of your strings:
This:
test~63~Dave Sanders~http://graph.facebook.com/998433599/picture?type=large~Dave Sanders~9 minutes ago
Could become this:
[
{
'name': 'test',
'id': 63,
'name': 'Dave Sanders',
'url': 'http://graph.facebook.com/998433599/picture?type=large',
'when': '9 minutes ago'
// other properties
},
{
// the next one
},
{
// etc.
}
]
It may look like more work, but you could use some JSON library for php (I'm guessing, since you use the term "explode") to build the JSON on the server. Then your returned content is already in a form for your browser-based client app to use with no additional effort. I find it hard to imagine that this will be more work in the end than what you're trying to do with the string manipulation, and JSON is likely to be less brittle.
As per your updated question...
You can still use JSON for this. I think it might help you to read the JSON specification
Adding to Chris Farmer's answer, JSON can be made of Arrays as well, so you can nest your comments in the response:
var response = [
{
'name': 'test',
'id': 63,
'name: 'Dave Sanders',
'url': 'http://graph.facebook.com/998433599/picture?type=large',
'comments' : [
'comment1',
'comment2',
'comment3',
...
]
},
...
]
You can then loop through the comments like this:
// loop through the images
for ( var i = 0; i < response.length; i++ ) {
var image = response[i];
// loop through the comments
for ( var z = 0; z < response.length; z++ ) {
var comment = image.comments[z];
// insert HTML here.
}
}
Do you see how much easier and less verbose this is than your current method?
Unfortunately to make this easier for yourself in the long run you will have to re-write your backend code. However, this will teach you the benefit and power of using JSON to transport information.

Categories