Retrieving the last set of key values from array using JQuery - javascript

complete noob currently trying to complete a Uni assignment. We are creating a web app using HTML, css and JQuery. I've searched the web for an answer but can't quite figure out what I'm supposed to do.
I have set up a page where users can type in details for a shift, when they submit it, the data is pushed onto an array stored in localStorage using JSON stringify. That part works great and here it is:
var shift = {'location':$('#shift_location').val(), 'start_time':$('#shift_start_time').val(), 'end_time':$('#shift_end_time').val()};
var shift_list = JSON.parse(localStorage.shift);
shift_list.push(shift);
localStorage.shift = JSON.stringify(shift_list);
However I then need to take the last 'shift_location' 'shift_start_time' and 'shift_end_time' that has been added and stick it in a div on the page.
This is what I have come up with so far:
var result = JSON.parse(localStorage.shift);
$.each(result, function(k, v) {
$('.current_shift').text(k + ":" + v);
});
However, all that appears on the page is: 0:[object Object].
Any ideas on how to sort this out would be great. Like I said I'm a complete noob and this is my first time posting on here so apologies in advance if I've missed out any important bits of code or framed the question incorrectly.
Thanks
James

You have an array of objects, you have to get the last object in the array first :
var result = JSON.parse(localStorage.getItem('shift'));
var obj = result.pop();
$('.current_shift').text(obj.start_time + ":" + obj.end_time);

This is an Array shift_list.
So it looks like locationStorage.shift is an array. That is why the k is an integer. Try this:
$.each(result, function(k, v) {
$('.current_shift').text(v.location);
});
You will see that it is an object since your shift is stored in Objects. For debugging you can do this:
$.each(result, function(k, v) {
console.log(v);
$('.current_shift').text(v.location);
});
Open Chrome, and look at the console, there you will see your objects.

Related

Passing a json array to javascript function in a jade rendered page

I have a json array being passed to a jade template.
This template then runs through the array adding rows to the html output.
However a new requirement no needs that json object to be passed to a javascript function, so I tried:
- var json = JSON.stringify(rows);
input.medium.success.button.error(type='submit', id='update_details', value= sendCommandLabel, onclick='sendCommand(' + json + ')')
which gives the following output (the full array omitted from brevity):
<input type="submit" id="update_details" value="Send Command" onclick="sendCommand([{"id":"id1;,"param1":value1, ... "}])">
Which is not useful as I am want to use this output in the javascript function and as it stands I can't consume it.
I am hoping I am missing something simple as my other option is to recreate the json array by looping through the objects in the renderer to recreate it!
UPDATE: I modified the code so instead of passing the array to the function, the array is hardcoded into the function while the jade page was being compiled. So this:
function sendStopCommandToAllSensors()
{
var hardcode = !{JSON.stringify(rows)};
became
function sendStopCommandToAllSensors()
{
var hardcode = [{"id":"id1", ... }, {"id":"id2", ... }];
But that still didn't work.
Puzzlingly adding a couple of simple alerts in there showed that there was the correct number of objects (later confirmed that there by cutting and pasting the resultant string directly into code and then manually adding a third object).
alert(hardcode.length); // displays 2
alert("rows: " + hardcode); // displays [object Object],[object Object]
Which is why in the loop that follows the
for (var row in hardcode)
{
alert("row: " + row); // displays 0 or 1, not an object
if (row.active == 1)
{
alert("Reached here"); // never reached
the final line is never reached.
UPDATE II: By stringifying hardcode I can output the human readable json.
alert("rows: " + JSON.stringify(hardcode));
Why is the code not seemingly parsing the array correctly and what to I do need to do correct it?
UPDATE III: I now having it working by using a two step traditional loop and assignment.
for (var i=0; i<rows.length; i++)
{
var row = rows[i];
So the question seems to be now, why didn't the for..in loop work as expected?
I am new to this, but I was going through similar problem I think.
But I am totally ok with JSON.stringify method, which was your first solution. It looks ugly in generated hmtl, but I found it useful in my case.
At least I think I understood it right and you are not trying to do some kind of magic what I can't absorb yet.
if
rows=[{id:id,param:param},{id:id2,param:param2}]
JADE:
- var json = JSON.stringify(rows);
input(type='submit', onclick='myFunction(' + json + ')')
JS:
function myFunction(myRows) {
console.log(myRows[0].id);
console.log(myRows[0].param);
console.log(myRows[1].id);
console.log(myRows[1].param);
.
.
at least it is ok in what I am working on.
I hope I didn't wrote pile of nonsense :)

How to parse a JSON array

new here and hit a roadblock, been searching but can't find the answer with my skill set. Task is pretty simple, I want to parse this http://data.sparkfun.com/output/AJ2p4r8Owvt1MyV8q9MV.json which is from a weather station. I have used the W3C tutorial but just can't seem to parse this file, but http://json.parser.online.fr has no problem. All the looping parse examples just give me alert after alert.
All I want is the ability to select temp[0] (out of god knows how many) for example via javascript and have it display on a website. I'm really lost, tried searching and if I've missed the goldmine then my bad. Thanks!
Example code
var text = '[{"humidity":"42.8000","stationtime":"2014-07-06 19:43:52","temp":"23.3000","timestamp":"2014-07-06T09:44:07.918Z"},{"humidity":"‌​43.0000","stationtime":"2014-07-06 19:42:57","temp":"23.2000","timestamp":"2014-07-06T09:42:22.003Z"},{"humidity":"‌​43.2000","stationtime":"2014-07-06 19:42:36","temp":"23.3000","timestamp":"2014-07-06T09:42:51.737Z"}]';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.temp[0];
First, you need to parse the incoming string as below:
temp_arr = JSON.parse(json_string);
Just loop over the temp_arr array, and in each iteration of loop you'll have one object (tobj). For example, like this:
{"humidity":"40.9000","stationtime":"2014-07-06 21:21:03","temp":"22.6000","timestamp":"2014-07-06T11:20:27.231Z"}
All you have to do is, access it like tobj.temp and use it to display on page.
I have written a jquery implementation at: http://jsfiddle.net/DNH5n/2/
Jquery makes working with JSONP much easier heres an example (http://jsfiddle.net/icodeforlove/9mBsr/)
$.getJSON('http://data.sparkfun.com/output/AJ2p4r8Owvt1MyV8q9MV.json?callback=?', function (data) {
data.forEach(function (item) {
$('body').append(JSON.stringify(item));
});
})
update again
heres another example using your code (http://jsfiddle.net/icodeforlove/9mBsr/2/)
var text = '[{"humidity":"42.8000","stationtime":"2014-07-06 19:43:52","temp":"23.3000","timestamp":"2014-07-06T09:44:07.918Z"},{"humidity":"‌43.0000","stationtime":"2014-07-06 19:42:57","temp":"23.2000","timestamp":"2014-07-06T09:42:22.003Z"},{"humidity":"‌43.2000","stationtime":"2014-07-06 19:42:36","temp":"23.3000","timestamp":"2014-07-06T09:42:51.737Z"}]';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj[0].temp;

Need to get an array of the names of all applicationScope variables

In an application I am working on I need to get a list of the names of all applicationScope variable then I need to cycle through them and filter out the ones starting with a know string say $xyx. I thought that the applicationScope.keySet().
I'm using this code for starter:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
if (itr.hasNext()){
var str:String = itr.next();
dBar.info(str,"Value = ");
}
if I put the variable col in a viewScope it shows a list of all the keys. but when I run the script the values displayed in the dBar info are not the keys but some other information that I'm not sure where it comes from.
I should just be able to iterat through the list of keys, am I missing something?
This code is in the before page loads event
After some poking around and experimenting I got this to work:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
while (itr.hasNext()){
var str:Map.Entry = itr.next();
if (str.substring(0,9) == "$wfsLock_"){
//do stuff
}
}
so I'm now a happy camper.
Although your code works in SSJS, it is not correct (and that's why I don't like SSJS...).
The applicationScope is an implementation of the java.util.Map interface and the keySet() method returns a Set containing the keys in that Map. Every entry is (probably) a String (other data types like integers are actually also valid). The line
var str:Map.Entry = itr.next();
doesn't cast it to a Map.Entry: it doesn't really do anything: str remains a string.
The Map interface also has an entrySet() method that returns the entries (Map.Entry). You can use that to retrieve the key as well as the value:
var it = applicationScope.entrySet().iterator();
while (it.hasNext()) {
var entry = it.next();
print( entry.getKey() + " = " + entry.getValue() );
}
(in this code the print() line will use the toString() method of the key as well as the value to send information to the console)
I see from your code that you've installed my XPages Debug Toolbar. You can also use that to quickly check what's in the scopes and what the actual datatype is.

Looping through multilayer json Jquery

Hi i'm quite new to jquery and json so please bear with me. I have searched the forums and tried a lot of different things to solve my problem.
I'm trying to loop through a multilayer JSON file form Freebase.
$.getJSON(service_url + topic_id + '?callback=?', params, function(topic) {
$("#free").append('<h3>Description</h3><p>'+topic.property['/common/topic/description'].values[0].value+'</p>');
$("#title").prepend('<h2>'+topic.property['/type/object/name'].values[0].value+'<span><a class="socila-link" style="color:#3b5998;" href="'+topic.property['/common/topic/social_media_presence'].values[0].value+'"> <i class="icon-facebook-sign"></i></a><a class="socila-link" style="color:#0084B4" href="'+topic.property['/common/topic/social_media_presence'].values[2].value+'"> <i class="icon-twitter-sign"></i></a></span></h2>')
$("#fb-span1").append('<p><strong>Official Website: </strong>'+topic.property['/common/topic/official_website'].values[0].value+'</p>');
$("#fb-span1").append('<p><strong>Genre: </strong>'+topic.property['/music/artist/genre'].values[0].text+'</p>');
$("#fb-span1").append('<p><strong>Founded: </strong>'+topic.property['/music/artist/active_start'].values[0].text+'</p>');
$("#fb-span1").append('<p><strong>Hometown: </strong>'+topic.property['/music/artist/origin'].values[0].text+'</p>');
$.each(topic.property, function(i, val) {
$("#fb-span1").append('<p><strong>Genre: </strong>'+val['/music/artist/genre'].values['text']+'</p>');
});
I have no problems getting the result if i enter the value like [0], but i cant seem to loop through it.Nothing gets returnet
Aside from the getJSON call you don't need any jQuery to do this. You can just access the JSON data as regular Javascript arrays and dictionaries. So to output multiple values from the array of "Genre" property values you can just use a for loop like this:
for (var i=0; i<topic.property['/music/artist/genre'].values.length; i++) {
var val = topic.property['/music/artist/genre'].values[i];
$("#fb-span1").append('<p><strong>Genre: </strong>'+val['text']+'</p>');
}

dump jquery object in an alert box

I am not quite adept in maneuvering jQuery, and it came to a point that I need to debug a program that was passed down from me without a documentation.
I have this var a, an object, that I really want to know the content of its collection. In my mind I need a function like foreach() in PHP to iterate over this object variable. Upon researching I end up in using jQuery.each(). Now I can clearly iterate and see what was inside var a.
However, it was kind of annoying to alert once every value on the var a. What I wanna know if it's possible to display all the contents in just one pop of alert box?
Here is my code:
$.each(a, function(index, value) {
alert(index + ': ' + value);
});
The var a contains infos such as:
creationdate: date_here
id: SWFUpload
modificationdate: date_here
type: .jpg
index: 0
name: uploaded_filename.jpg
size: size_in_bytes
BTW: The var a is called via file upload script.
Why don't you just accumulate the values in an array, then display the whole array (for instance, using JSON)? Example:
var acc = []
$.each(a, function(index, value) {
acc.push(index + ': ' + value);
});
alert(JSON.stringify(acc));
In any case, I'd suggest using a debug tool like Firebug. So you could just use console.log(a) and be able to navigate freely through the objects's fields.
In firefox you could try:
alert(yourObject.toSource());
OR you could use some plugin:
See: jQuery Dump Plugin

Categories

Resources