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);
})
Related
I am trying to use the data attribute to change the page to details about the selected product in my index web page.
These are the functions that I am using at the moment. This works but it will only display the innerHTML of the document. Whereas i want all of the data about the object that is stored in a data attribute called data-detail. The responseText would be something similar to this:
data-detail='{"ID":"1", "Name":"Some Name", "Description":"Some Description", "Price":"100", "Photo":"SomePath/AnotherPath/Image.png"}'
function displayItems(results){
article = document.getElementById("homeSection");
string = '<h1>Company Name</h1><h2>Why not try these products?</h2>';
for(var i=0; i<results.length; i++){
var price = parseFloat(results[i].Price);
var sec = document.createElement("section");
sec.classList.add("homeItem");
sec.dataset.detail = JSON.stringify(results[i]);
article.appendChild(sec);
sec.innerHTML = '<div class="imageContainer"><img class="resultsImage" src="' + results[i].Photo + '"></div><p class="resultsName">' + results[i].Name + '</p><p class="resultsPrice">£' + price.toFixed(2) + '</p>';
var items = document.querySelectorAll(".homeItem");
for(i=0; i<items.length; i++){
items[i].addEventListener("click", selectedProduct);
}
}
}
function selectedProduct(event){
target = event.currentTarget;
homeSection = document.getElementById("homeSection");
console.log(target.detail.ID);
homeSection.innerHTML = target.innerHTML;
}
After clicking on an element, the console is telling me that data.detail is undefined after parsing through the 3rd line down in the selectedProduct function. I wonder if anyone could tell me why this is and if I am being silly and not spotting the problem.
As you can store only string values, So after getting the value, you need to convert back to object by calling JSON.parse(). You also need to use dataset to get the value as you are setting the value.
function selectedProduct(event){
target = event.currentTarget;
homeSection = document.getElementById("homeSection");
console.log(JSON.parse(target.dataset.detail).ID);
homeSection.innerHTML = target.innerHTML;
}
I get the following json data from server.
{"visits":[{"City":6,"Count":5},{"City":16,"Count":1},{"City":23,"Count":1},{"City":34,"Count":1}]}
and i need to convert it to following format:
{"1":"82700","2":"26480","3":"31530","4":"22820","5":"15550","6":"205790"}
I have the following code but not working out:
var cities = "{";
for (var key in data.visits) {
var val = data.visits[key];
//Now you have your key and value which you
//can add to a collection that your plugin uses
var obj = {};
obj[val.City] = '' + val.Count;
var code = '' + val.City;
var count = '' + val.Count;
cities += code + ':' + count + ',';
}
cities += "}";
I need the integers in string representation and need to get rid of the final , .
How can i fix this?
Try this
var data = {"visits":[{"City":6,"Count":5},{"City":16,"Count":1},{"City":23,"Count":1},{"City":34,"Count":1}]};
var result = {};
for (var i = 0; i < data.visits.length; i++) {
result[data.visits[i].City] = String(data.visits[i].Count);
}
Example
Keys in object always converts to string you don't need convert it to string manually. If you need convert all object to JSON string you can use JSON.stringify(result);
How I understood you want to create new json with given json.you can parse it,run with cycle on it,and create a new json whatever kind of you want.
here is a link which can help you.
http://www.w3docs.com/learn-javascript/working-with-json.html
This question already has answers here:
How to store objects in HTML5 localStorage/sessionStorage
(24 answers)
Closed 8 years ago.
I have several large multi-dimensional arrays that I'm saving to local storage. They look like this:
[[[-150],[0],[-650],0],[[-100],[0],[-650],0],[[-50],[0],[-650],0] ... ]
The data is '4D' data. When I try loading this 'string' into an array in another JS (in separate html), it doesn't behave like an array- it's only a string.
Here's how I load the data back into the second JS (not sure why the loop didn't work either):
var lay= new Array();
//for(var g=0;g>=9;g++)
//{ lay[g] = localStorage.getItem("key" + g);
// console.log(lay[g]);
//}
lay[0] = localStorage.getItem("key0");
lay[1] = localStorage.getItem("key1");
lay[2] = localStorage.getItem("key2");
//... more here
lay[9] = localStorage.getItem("key3");
After I load this "4D" info into the array, I pull the info out to use it:
var count=0;
var len=0;
for (y=0;y<=1;y++)
{ console.log(lay[y]);
count=1;
len = lay[y].length;
for (x=1;x<=len-1;x++)
{
Rx = lay[y][count][0];
Ry = lay[y][count][1];
Rz = lay[y][count][2];
Rcolor = lay[y][count][3];
When I add this to the code console.log(len); I get the length of characters in the array, not the number of elements. How can I get the data from local storage to come in and behave like array? I thought that the formatting alone would get it behave like an array.
Do I need to parse it back into an array again? If so, I'm guessing I should just output the data in a simpler format to parse it again...
Thanks for the help!
Edit
Here's how I made the local storage:
for (var a=0;a<=14;a++)
{ updateTemp(tStep + a);
$("#temp tbody tr").each(function(i, v){
data[i] = Array();
$(this).children('td').each(function(ii, vv){
data[i][ii] = $(this).text();
rows=ii;
cols=i;
});
});
retval="";
for (var q=0;q<=cols;q++)
{
for (var w=0;w<=rows;w++)
{
var tempv = data[q][w];
var tX = w*50 - 1000;
var tY = 1*50 - 50;
var tZ = q*50 - 1000;
if (tempv==-9){
(dummy=q*w);
}
else {retval += tX +',' + tY + ',' + tZ + ',' + tempv + ',';}
}
}
var kee = "key" + a;
retval = retval.substring(0, retval.length-1); //this is to get rid of the last character which is an extra ,
window.localStorage.setItem(kee, retval);}
JSON encode the array before storing, parse after retrieving.
localStorage.test = JSON.stringify([1,2,3]);
console.log(JSON.parse(localStorage.test));
This is a duplicate of “Storing Objects in HTML5 localStorage”. localstorage only handles strings. As suggested there, serialise your array to a JSON string before storing.
I currently have the bellow code to get some data from an xml feed.
var title = []
var start = []
var end = []
var xml = result;
var channel = xml.split('<channel')[1].split('>')[0].split('"')[1]
var xmlLength = xml.split("<programme>").length - 1;
for (var i = 0; i < xmlLength; i++) {
var event = xml.split("<event>")[i + 1].split("</event>")[0];
title[i] = programme.split("<title>")[1].split("</title>")[0];
var rs = programme.split("<start>")[1].split("</start>")[0].split(/\-|\s/);
var re = programme.split("<end>")[1].split("</end>")[0].split(/\-|\s/);
start[i] = new Date(rs.slice(0, 3).join('/') + ' ' + rs[3]);
end[i] = new Date(re.slice(0, 3).join('/') + ' ' + re[3]);
}
setListView(event, start, end, channel)
This currently works but it doesn't seem very efficient. I wonder if there is a better way of doing it.
Well, it looks like you should be using the classes in the Windows.Web.Syndication namespace as it looks like you are doing RSS related things, but you could also use the raw XML API's as well.
It seems like you are trying to parse the XML on your own. Have you considered using jQuery.parseXML()?
Check it out here: http://api.jquery.com/jQuery.parseXML/
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);
}