AngularJS set localstorage (object json) - javascript

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.

Related

How to fetch values from json array object without using object key name javascript?

Json Array Object
Through Ajax I will get dynamic data which is not constant or similar data based on query data will change. But I want to display charts so I used chartjs where I need to pass array data. So I tried below code but whenever data changes that code will break.
I cannot paste complete JSON file so after parsing it looks like this
[{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
You can use Object.keys and specify the position number to get that value
var valueOne =[];
var valueTwo = [];
jsonData.forEach(function(e){
valueOne.push(e[Object.keys(e)[1]]);
valueTwo.push(e[Object.keys(e)[2]]);
})
It seems like what you're trying to do is conditionally populate an array based the data you are receiving. One solution might be for you to use a variable who's value is based on whether the value or price property exist on the object. For example, in your forEach loop:
const valueOne = [];
jsonData.forEach((e) => {
const val = typeof e.value !== undefined ? e.value : e.average;
valueOne.push(val);
})
In your jsonData.forEach loop you can test existence of element by using something like:
if (e['volume']===undefined) {
valueone.push(e.price);
} else {
valueone.push(e.volume);
}
And similar for valuetwo...
You could create an object with the keys of your first array element, and values corresponding to the arrays you are after:
var data = [{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
var splitArrays = Object.keys(data[0]).reduce((o, e) => {
o[e] = data.map(el => el[e]);
return o;
}, {});
// show the whole object
console.log(splitArrays);
// show the individual arrays
console.log("brand");
console.log(splitArrays.brand);
console.log("volume");
console.log(splitArrays.volume);
// etc

javascript - JSON file use a value only if key exists

I'm retrieving an OSM Json from an overpass call, to obtain a list of features that I have to save on a database. Since the data are very different from one another (for example, some of them do have a a tag called "addr:city", and some of them not), I would like to check if a key exists, and only in that case save the corresponding value. I've found only this question but it's not my case, since I do not know a priori which keys one element will have and which not, and since I'm working with a great load of data, I really can't check the elements one by one and of course I can't write an IF for each case.
Is there a way to solve this? I was thinking something about "if key has null value, ignore it", while looping over the elements, but I don't know if something like that exists
EDIT:
This is my query:
https://overpass-api.de/api/interpreter?data=[out:json][timeout:25];(node[~%22^(tourism|historic)$%22~%22.%22](44.12419,%2012.21259,%2044.15727,%2012.27696);way[~%22^(tourism|historic)$%22~%22.%22](44.12419,%2012.21259,%2044.15727,%2012.27696););out%20center;
and this is the code I'm using to save the data on firebase:
results.elements.forEach(e=>{
var ref = firebase.database().ref('/point_of_interest/');
var key = firebase.database().ref().child('point_of_interest').push().key;
var updates = {};
var data = {
città: e.tags["addr:city"],
tipologia: e.tags["amenity"],
indirizzo: e.tags["addr:street"],
nome: e.tags["name"],
lat: e.lat,
lon: e.lon
}
updates['/point_of_interest/'+key] = data;
firebase.database().ref().update(updates);
})
"results" is the response in json format
You could use something like that:
var attrs = ["addr:city", "amenity", "addr:street", "name"];
var labels = ["città", "tipologia", "indirizzo", "nome"]
var data = { };
attrs.forEach((a, i) => {
if (e.tags[a]) { data[labels[i]] = e.tags[a]; }
});
You could even make this more dynamic, if you can query the attribute names and labels from somewhere.

Jquery print object

I pass from php to js object. For example :
{"3199":{"name":"Ramona RONDEREGGER","mail":"mona.schlaepfer#bluewin.ch","phone":null,"hope":null
,"status":"NEW LEAD"},"3253":{"name":"Olivia
BAUMANN","mail":"oliviazurfluh#gmail.com","phone":null,"hope"
:null,"status":"NEW LEAD"}}
And I want to get data from this object in js (get 3199, 3253 and their data (name,mail ...).
How can I do it?
I try it:
$(data).each(function(key,value){
$(value).each(function(key,value){
console.log(value);
});
});
But id doesn't work
Please, help me to solve this problem
Thanks
Iterate through your object and get data by key. Here is the example of your dataset showed that how can you access the data in your result object.
var data = {"3199":{"name":"Ramona RONDEREGGER","mail":"mona.schlaepfer#bluewin.ch","phone":null,"hope":null
,"status":"NEW LEAD"},
"3253":{"name":"Olivia BAUMANN","mail":"oliviazurfluh#gmail.com","phone":null,"hope"
:null,"status":"NEW LEAD"}};
for(x in data){
// this will print your key
console.log("this is your key " + x);
// this line will print your key object
console.log(data[x]);
//to access internal element
console.log(data[x]['mail']);
}
Specify key like this value["3199"]
var data = {"3199":{"name":"Ramona RONDEREGGER","mail":"mona.schlaepfer#bluewin.ch","phone":null,"hope":null,"status":"NEW LEAD"},"3253":{"name":"Olivia BAUMANN","mail":"oliviazurfluh#gmail.com","phone":null,"hope"
:null,"status":"NEW LEAD"}};
$(data).each(function(key,value){
$(value).each(function(key,value){
console.log(value["3199"]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Get values from a HashTable saved in a session variable

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);

Store values in javascript object with same keys

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"];

Categories