In asp.net (vb.net) I have a Session variable that contain a HashTable
Dim products As Hashtable = New Hashtable
products("example") = "One product"
Session("products") = products
Now I want to obtain in client side with javascript, the value of products("example").
I try this:
<SCRIPT>
function ShowSessionValue() {
// new object
var sessionHashT = {};
// asign HashTable stored in Session("products") to "sessionHashT"
sessionHashT= '<%=Session("products")%>';
// All alerts show "undefined" (but no errors):
alert(sessionHashT("example"));
alert(sessionHashT(example));
alert(sessionHashT.example);
};
</SCRIPT>
With a breakpoint I see that the value of sessionHashT is :
sessionHashT = 'System.Collections.Hashtable';
How I can get the values of the HashTable with javascript?
Untested, but you could serialize your HashTable to JSON to include in your script:
// assign HashTable stored in Session("products") to "sessionHashT"
sessionHashT= JSON.parse('<%= New JavaScriptSerializer().Serialize(Session("products"))%>');
I suppose you could get away with not parsing it (note the lack of quotes):
// assign HashTable stored in Session("products") to "sessionHashT"
sessionHashT= <%= New JavaScriptSerializer().Serialize(Session("products"))%>;
You should then be able to use the dotted form to access the items by key:
alert(sessionHashT.example);
Related
based on this answer, I want to convert store data to object and defined the key value as well. Here's my related code :
var recordArray = {};
var paramArray = [];
store.each(function(record){
recordArray.comment = record.get("comment");
recordArray.datecreated = record.get("datecreated");
paramArray.push(recordArray);
});
console.log(Ext.encode(paramArray));
But the printed out is only last data from store, with sum matches with data sum. Suppose I have 2 data from list view like this :
[{comment: a, datecreated:1-2-1999}, {comment: b, datecreated:2-2-1999}]
The print out :
[{comment: b, datecreated:2-2-1999}, {comment: b, datecreated:2-2-1999}]
What I want, of course, the paramArray contains every object of listView, not just a same one. Any ideas? Help appreciated.
Try this,
var paramArray = [];
store.each(function(record){
var recordArray = {};
recordArray.comment = record.get("comment");
recordArray.datecreated = record.get("datecreated");
paramArray.push(recordArray);
});
In your code, you are overwriting the values in the original recordArray object instead of creating a new object everytime and since objects are passed by reference in JavaScript, the original recordArray reference at paramArray[0] also gets modified.
I have a constructor like this
function Employee(name, rank, mf)={
this.name=name;
this.rank=rank;
this.mf=mf;
}
How can I create a new employee and storing the name, rank, and mf in an object with the ability to change it later on? Keep in mind i'm creating the new employee through a function so i can't just create a new var manually. THx.
This is how i create a new employee
function employee(){
var name=prompt("Last, First");
var rank=prompt("Rank");
var mf=prompt("M/F");
var ID=prompt("ID");
var confirming=confirm("ID: "+ID+"Name: "+name+"Rank: "+rank+", "+mf);
if(confirming){
new Employee(name, rank, mf);
}else{
console.log("Employee addition cancled")
}
}
You have a typo in your constructor code which can cause you compilation (syntax) error. Note the equal = sign. Should be
function Employee(name, rank, mf) {
Q: How can I create a new employee and storing the name, rank, and mf in an object with the ability to change it later on?
A: You'll need to maintain a reference to that new object by storing it into a variable. You can achieve it by doing
var myEmployee1 = new Employee(...);
So from there you could access that same object through calling the variable like myEmployee.name
If you are having a function to take on the create employee object role then you can either modify that function to, return the newly created object or populate straight into a global variable. My preference would be the former as it is much cleaner.
Also, tracking the employee objects in an array is 1 strategy you can use but depending on how many objects you are expected. Finding an object in an array may not be as efficient as storing them in a {} dictionary data structure. As you are required to loop through individual objects from an array before finding the right one, whereas dictionary you access objects straight from the key, essentially transversing a tree which is quicker in most scenario.
Obviously storing an employee object through using the name as the key can be dangerous because names are never unique. Instead you should be using the unique identifier Id.
Example:
function employee(){
...
return new Employee(name, rank, mf);
}
var myDictionary = {};
var emp = employee();
myDictionary[emp.id] = emp; // Store the employee object by its key with value = the object itself.
// To access the very same employee object next time. Let say the id is 10 then you would do...
console.log(myDictionary[10].name)
You need to maintain global array for object reference this check my sample code :
var objRef=[];
function employee(){
var name=prompt("Last, First");
var rank=prompt("Rank");
var mf=prompt("M/F");
var ID=prompt("ID");
var confirming=confirm("ID: "+ID+"Name: "+name+"Rank: "+rank+", "+mf);
if(confirming){
objRef[name]=new Employee(name, rank, mf); //access using objRef['alen']
}else{
console.log("Employee addition cancelled.")
}
}
//Your constructor.
function Employee(name, rank, mf)
{
this.name=name;
this.rank=rank;
this.mf=mf;
}
and you can access your object by simply objRef[name]. you can make id as key .
I am using JavaScript serializer to send value to JavaScript:
JavaScriptSerializer oSerializer = new JavaScriptSerializer();
var Result = (from c in dt.AsEnumerable()
select new
{
Latitude = c.Field<Decimal>("Latitude"),
Longitude = c.Field<Decimal>("Longitude")
}).ToList();
hdnControl.Value = oSerializer.Serialize(Result);
This results in this kind of value:
[
{"Latitude":19.2094000000,"Longitude":73.0939000000},
{"Latitude":19.2244070000,"Longitude":73.1545760000},
{"Latitude":32.5838493257,"Longitude":132.3632812500},
{"Latitude":59.3331894266,"Longitude":8.6572265625}
]
How can I retrieve these values in a JavaScript function?
Are there any inbuilt method to access it
or do I need to use the .split() function to get the values?
Any help will be appreciated.
This is javascript json array. You can use forEach to retrieve the value using the keys
a.forEach(function(item){
document.write('<pre> Latitute is '+item.Latitude+'</pre>')
})
A complete list of of array methods is available HERE which can be used as required
JSFIDDLE
How can I change/modify/refresh my localstorage of AngularJS?
My localstorage content is an object json:
//data content: {Id:1,Name:"Juanito"}
localStorageService.set("MyObj",data);
console.log(localStorageService.get("MyObj"));
//SHOW object JSON {Id:1,Name:"Juanito"}
But if I modify a unique key like this:
localStorageService.set("MyObj.Id","otherid"),
It does not work. How do I fix this?
Try retrieving, then updating and re-setting:
var data = {id: 123}
localStorageService.set("MyObj",data);
var dataFromLS = localStorageService.get("MyObj");
dataFromLS.id = 456;
localStorageService.set("MyObj",data);
console.log(localStorageService.get("MyObj"));
When you change/modify your key name, a brand new object will be created/stored in your service.
If you want to change/alter key's data/value, perform intermediate operations and set it with same key.
I have the following code to extract values from a JSON response. What I am trying to do is store the data in a similar way to how you would with an associative array in php. Apologies for the code being inefficient. The array comments written down are how I would like it to look in the object.
$.each(responseData, function(k1,v1){
if(k1 == "0"){
$.each(v1, function(k2,v2){
$.each(v2, function(k3, v3){
if(k3 == "val"){
//store in object here
//Array1 = array("time"=>k2, "iVal"=>v3)
console.log(k3 + v3 + k2);
}else{
//Array2 = array("time"=>k2, "aVal"=>v3)
console.log(k3 + v3 + k2);
}
});
});
}
});
So all the information is there but I am not sure how to store each instance for the values in an object. I did try store it like this:
//obj created outside
obj1.date = k2;
obj2.iVal = v3;
But doing this clearly overwrote every time, and only kept the last instance so I am wondering how can I do it so that all values will be stored?
Edit: Added input and output desired.
Input
{"0":{"18.00":{"iVal":85.27,"aVal":0.24},"19.00":{"iVal":85.27,"aVal":0.36},"20.00":{"iVal":0,"aVal":0}}, "success":true}
Desired output
array1 = {"time":"18.00", "iVal":85.27},{"time":"19.00", "iVal":85.27},{"time":"20.00", "iVal":0}
array2 = {"time":"18.00", "aVal":0.24},{"time":"19.00", "aVal":0.36},{"time":"20.00", "aVal":0}
try this :
var g1=[];
var g2=[];
for ( a in o[0])
{
g1.push({time:a , iVal:o[0][a]['iVal']})
g2.push({time:a , aVal:o[0][a]['aVal']})
}
http://jsbin.com/qividoti/3/edit
a json response can be converted back to a js object literal by calling JSON.parse(jsonString) inside the success callback of your ajax call.
from then on there is no need for iterating over that object since you navigate it like any other js object which is can be done in two ways either
the js way -> dot notation
var obj = JSON.parse(jsonStirng);
var value = obj.value;
or like a php array
var value = obj["value"];