I'm storing json strings representing objects in the local storage. I write something like this:
window.localStorage.setItem('ItemID' + TheItemID, TheItemInJson);
Now I need to know which items are in the storage. What's a good way to do this?
Thanks.
You would like to use this code:
for(var i=0, len=localStorage.length; i<len; i++) {
var key = localStorage.key(i);
var value = localStorage[key];
console.log(key + " => " + value);
}
Related
I want to set cookies. I have an array and a function setCookies. In this function, I loop through myCookies array and after some manipulation I get a string. This string supposed to set cookies.
const myCookies =
[
{budgetMonth: someValue1},
{budgetDay: someValue2},
{expensesMonth: someValue3}
];
function setCookies(myCookies) {
let arr = [];
for(let i of Object.keys(myCookies)) {
let myItems = myCookies[i];
for(let y of Object.keys(myItems)) {
arr.push('document.cookie ' + '= "' + y + '=' + myItems[y] + "\"");
}
}
let stri = '';
arr.forEach(item => {
stri += item + ';'
});
return stri;
}
setCookies(myCookies);
When I log stri I see the strings listed below. Isn't it a right way to set cookie? I guess it is, but why it doesn't work? When I just type in my code document.cookie = "budgetMonth=someValue1" the cookie is set.
document.cookie = "budgetMonth=someValue1";
document.cookie = "budgetDay=someValue2";
document.cookie = "expensesMonth=someValue3";
There are several issues with your code.
the structure in which you are storing the values for the cookies is not necessarily incorrect, but writing it as myCookies = {name1: value1, name2: value2} simplifies your code, indirectly verifies if you aren't setting the same cookie name multiple times (unless you really want to do that, setting multiple paths, for the same key, for example), and allows you to add/remove a cookie from the list later on in your code in a much more simplified way;
you are generating an array, and with that array, a string, but you aren't doing anything with any of them. To actually set up the cookie, you have to execute the code document.cookie = something.
A very simplified version of your code (untested) would be something like:
const myCookies = {
budgetMonth: someValue1,
budgetDay: someValue2,
expensesMonth: someValue3
};
function setCookies(myCookies) {
for(let k of Object.keys(myCookies)) {
document.cookie = k + "=" + myCookies[k];
}
}
setCookies(myCookies);
I am trying to perform a simple addition on data I have gathered from an external source via JSON. The data I am getting is being returned as a string but is a number so I have tried using both parseInt() and Number() to no avail. I have shown a simple section of the code below:
var total_energy = 0;
var energy_val;
$.each(result.report.food.nutrients, function (i, v) {
if (v.name == "Energy"){
energy_val = v.value;
var energy = Number(energy_val);
total_energy = total_energy + energy;
console.log("energy " + energy);
console.log("totalenergy " + total_energy);
energy_val = "";
energy = 0;
}
}
The console returns the correct value for energy each time but the totalenergy value just seems to stay the same as the energy value. The sum doesn't seem to have any affect. Could anyone tell me where I am going wrong with this problem?
change console.log("energy " + total_energy); to console.log("energy " + energy);
try parseInt your values... can be this
I doubt if its due to the closure created in the loop where you are iterating over the items. Try the following code.
var total_energy = 0;
var energy_val;
$.each(result.report.food.nutrients, function (i, v) {
var item = v;
//Calling calculateEnergy() function so that each 'item' is the current instance 'v' value.
(function calculateEnergy(itemClicked))(item);
}
function calculateEnergy(itemClicked){
if(itemClicked.name == "Energy"){
energy_val = itemClicked.value;
var energy = Number(energy_val);
total_energy = total_energy + energy;
console.log("energy " + energy);
console.log("totalenergy " + total_energy);
energy_val = "";
energy = 0;
}
}
I have put comments within the code.
Update console.log() is buggy with ajax requests. So instead of logging, try creating an html div and populate the values there.
I am trying to add/append to new/existing localStorage using this code:
function add(){
var name = document.getElementById("name").value;
var ort = document.getElementById("ort").value;
var user = {"name":name, "ort":ort};
var exist = [];
var tmp = (JSON.parse(localStorage.getItem("users")));
if(tmp)
exist.push(tmp);
exist.push(user);
localStorage.setItem("users",JSON.stringify(exist));
console.log(JSON.parse(localStorage.getItem("users")));
var obj = JSON.parse(localStorage.getItem("users"));
for(var i=0; i<obj.length; i++) {
console.log('key: ' + i + '\n' + 'value: ' + obj[i]);
}
}
Looking into Chrome developer tools localStorage looks like this:
[[{"name":"a","city":"a"}],{"name":"b","city":"b"}]
But what I want is:
[{"name":"a","city":"a"},{"name":"b","city":"b"}]
What am I doing wrong?
Any help appreciated,
Best regards,
localStorage only store strings. You need to stringify your exist and then save it to storage
localStorage.setItem("users",JSON.stringify(exist));
To retrieve it use JSON.parse
var exist = JSON.parse(localStorage.exist); //Even for users object do the same
Update
To only push the objects inside the array tmp to exist use map():
tmp.map(function(item){
exist.push(item);
})
I have data structures similar to the code below that I want to iterate through with Handlerbars. While the javascript code that can do this iteration is clear, I have not been able to figure out how to do it in handlebars.
var keys = ['key1','key2','key3']
var map = {'key1':{...}, 'key2':{...}, 'key3':{...}, .... 'keyN': {...}}
What I want to do within handlebars is to iterate the keys array and use the value from the keys array to look-up the object from the map. Can this be done without writing a helper?
UPDATE I know how to write the code in javascript, I want to do is "what i can do in raw js using handlebarJS expressions".
try this :
for(var i=0; i<keys.length; i++){
console.log(map[keys[i]])
}
Handlebars.registerHelper('list', function(keys, maps) {
var out = "<ul>";
for(var i=0, i=keys.length; i++) {
out = out + "<li>" + map[keys[i]] + "</li>";
}
return out + "</ul>";
});
How can I display object content without specifying the attributes ? (The object here is used as associative array)
alert(result[0].name);
alert(result[0].surname);
I actually would like to not have to write "name" and "surname", but display all the content (keys & values)
thanks
Try this.. (it uses for each loop):
var arr=[];
arr[0] = 'Test1';
arr['SomeKey'] = 'Test2';
for(var o in arr)
{
var val = arr[o];
alert("Key is: " + o);
alert("Value is: " + val);
for(var b in val)
{
alert("Inner Key is: " + b);
alert("Inner Value is: " + val[b]);
}
}
Maby this will help you:
for (var item in result[0]) {
var key=item;
var val=b[item];
alert('b['+key+']='+val);
}
Good luck!
Maybe as a clarification for the other answers:
result[0].name
is the same as
result[0]["name"]
However,
result[0][name]
would use whatever the current value of name is. E.g.
var name = "surname";
if (result[0][name] == result[0].surname) // this is true