dynamic array to local storage/jstorage? - javascript

I am pushing values in to my array every 10 seconds which is being displayed by innerHTML on a div.
Onreload or on visit to some other web page I want to display the already pushed content and the content being pushed presently.
I have gone through local stroage and jstorage tutorials.
This is what I am doing precisely=:
localStorage.setItem('names', xyz);
I know how to store one variable,but what when we have a dynamic array being updated/10sec and data being pushed in it every 10 seconds.how do I set and get this dynamic array even when I go to some other link.
If you are interested in my code:http://jsfiddle.net/vCcnB/
UPDATE 1----for simplification(ignore if you have understood.)
This is what is being displayed in my div.Page1 indicates the page and 0,10,20 indicates time.
# 10 seconds----[page1,0]
[page1,10]
#20 seconds-----[page1,0]
[page1,10]
[page1,20]
now a click to some other page.
#10 seconds----[page1,0]
[page1,10]
[page1,20]
[page2,0]
[page2,10]
now a click to some other page.
#20 seconds----[page1,10]
[page1,20]
[page2,0]
[page2,10]
[page3,0]
[page3,10]
[page3,20]

You can use json object for this like,
localStorage.setItem('names', {'ABC','XYZ'}); //and so on
or json string like
var json={'ABC','XYZ'};
localStorage.setItem('names', JSON.stringify(json)); //and so on
To get an existing item try this,
console.log(localStorage.getItem('names'));
Read this https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Storage

You have to JSON.stringify and JSON.parse your array to store and load it respectively.
// initialize
var myArray = [];
// load saved array
if(window.localStorage["savedArray"] != null)
myArray = JSON.parse(window.localStorage["savedArray"]);
// modify array
myArray.push("abc123");
// re-save array
window.localStorage["savedArray"] = JSON.stringify(myArray);

Related

How to append to an array every minute on every reload of page in Javascript?

I have a HTML code which is taking stock price which is updating every 1 minute ( on reload of page ). I want to make a graph out of the stock price. For this I would want to make an array in the morning and then as and when prices are updated every minute, the array is updated too. How can I do it? I tried to use local storage but just unable to get the desired results.
vwap_ltp_percentage is the variable here which I am getting every minute and which I want to append to an array
vwap_ltp_array = Array()
vwap_ltp_array.push(vwap_ltp_percentage)
console.log(vwap_ltp_array)
if (localStorage.getItem('test') == null) {
localStorage.setItem('test',[])
}
else {
localStorage.setItem('test',[])
}
localStorage.setItem("test", JSON.stringify(vwap_ltp_array))
console.log(localStorage)
ge)
In your case, you are always starting with an empty array, the if...else construct is not doing anything...
Instead, you need to construct the initial array from the storage if an entry exists there.
var testString = localStorage.getItem('test');
vwap_ltp_array = testString ? JSON.parse(testString) : []
vwap_ltp_array.push(vwap_ltp_percentage)
localStorage.setItem("test", JSON.stringify(vwap_ltp_array))
console.log(localStorage)

How to remove specific item from local storage array?

I'm building a 'to do list' , The user appends new notes to the list after clicking .
I saved all the appended data in the local storage.
Now i want to remove the clicked note from the array and save it back to the local storage.
I have this code:
**//Here i get the note**
var getNote = JSON.parse(localStorage.getItem("savedNotes")) || [];
$("#notes-section").append(getNote);
**//Here i set the note**
getNote.push(note);
localStorage.setItem("savedNotes", JSON.stringify(getNote));
**//Here i want to remove the note from the array**
$(document).on('click', '.pin', function() {
$(this).parent().css({opacity: 1.0, visibility: "visible"}).animate({opacity: 0}, 2000);
for(var i =0 ; i < getNote.length; i++ ){
getNote.splice(i,1);
localStorage.setItem("savedNotes", JSON.stringify(getNote));
}
});
As stated in comments you need to provide only relevant code, but just to clear things out here, the way to go here is:
To have an empty array of notes.
Add this array to localStorage via localStorage.setItem("savedNotes", JSON.stringify(notes)).
Every time you add a note you will need to: parse this array back from localStorage with notes = JSON.parse(localStorage.getItem("savedNotes")).
Then push the new note into this array via notes.push(note).
Then set this item again with localStorage.setItem("savedNotes",
JSON.stringify(notes)), it will update your existing item in the localStorage.
It all relies on Storage.getItem() and Storage.setItem() methods.
And to remove a note from the array you need to do the same thing, expect that you will search for this note in the parsed array and remove it.

LocalStorage error and idea

This is my code:
// store item
localStorage.setItem("blog_key", "value I am storing");
// retrieve item
var data = localStorage.getItem("blog_key");
I'm trying to make it list of array for the post, so when somenone click post, it will serve as blog post
Not sure if I got your question or not but I guess you want to do something like this:
// retrieve the local storage value or "[]" and then parse it
var data = JSON.parse(localStorage.getItem("blog_key") || "[]");
// add new item to the array - might want to make sure that the array wont grow too big
data.push("something new");
// store item as string
localStorage.setItem("blog_key", JSON.stringify(data));
I might be wrong though, but that's what I got from your question.

how to remove element from session storage array when there are lot of

I am trying to remove elements from localStorage array. all i could find is localStorage.removeItem(key);
I couldn't understand how it works because I have 2 sessionStorage. is that okay?
I have this so far
var theCart = JSON.parse(sessionStorage.getItem("ProductName")); // Retrieving
var quantity = JSON.parse(sessionStorage.getItem("QuantityOFprod"));
var prodprice = JSON.parse(sessionStorage.getItem("sum"));
ProductName, QuantityOFprod and sum is arrays.
I don't now how to form the localstorage.removeItem to select the array and then select an element inside the array. I have tried this
sessionStorage.removeItem("ProductName", JSON.stringify(namee));
namee is the a variable which contains the element I want to delete inside the specific sessionStorage array. But all it was doing is deleting everything.
You have to do this way:
read the entry
decode from JSON
remove the element
encode to JSON
update the entry
tmp = JSON.parse(sessionStorage.getItem("ProductName"));
delete tmp["key to remove"];
sessionStorage.setItem("ProductName", JSON.stringify(tmp));
Done.

Javascript pushing objects into array changes entire array

I'm using a specific game making framework but I think the question applies to javascript
I was trying to make a narration script so the player can see "The orc hits you." at the bottom of his screen. I wanted to show the last 4 messages at one time and possibly allow the player to look back to see 30-50 messages in a log if they want. To do this I set up and object and an array to push the objects into.
So I set up some variables like this initially...
servermessage: {"color1":"yellow", "color2":"white", "message1":"", "message2":""},
servermessagelist: new Array(),
and when I use this command (below) multiple times with different data called by an event by manipulating servermessage.color1 ... .message1 etc...
servermessagelist.push(servermessage)
it overwrites the entire array with copies of that data... any idea why or what I can do about it.
So if I push color1 "RED" and message1 "Rover".. the data is correct then if I push
color1"yellow" and message1 "Bus" the data is two copies of .color1:"yellow" .message1:"Bus"
When you push servermessage into servermessagelist you're really (more or less) pushing a reference to that object. So any changes made to servermessage are reflected everywhere you have a reference to it. It sounds like what you want to do is push a clone of the object into the list.
Declare a function as follows:
function cloneMessage(servermessage) {
var clone ={};
for( var key in servermessage ){
if(servermessage.hasOwnProperty(key)) //ensure not adding inherited props
clone[key]=servermessage[key];
}
return clone;
}
Then everytime you want to push a message into the list do:
servermessagelist.push( cloneMessage(servermessage) );
When you add the object to the array, it's only a reference to the object that is added. The object is not copied by adding it to the array. So, when you later change the object and add it to the array again, you just have an array with several references to the same object.
Create a new object for each addition to the array:
servermessage = {"color1":"yellow", "color2":"white", "message1":"", "message2":""};
servermessagelist.push(servermessage);
servermessage = {"color1":"green", "color2":"red", "message1":"", "message2":"nice work"};
servermessagelist.push(servermessage);
There are two ways to use deep copy the object before pushing it into the array.
1. create new object by object method and then push it.
servermessagelist = [];
servermessagelist.push(Object.assign({}, servermessage));
Create an new reference of object by JSON stringigy method and push it with parse method.
servermessagelist = [];
servermessagelist.push(JSON.parse(JSON.stringify(servermessage));
This method is useful for nested objects.
servermessagelist: new Array() empties the array every time it's executed. Only execute that code once when you originally initialize the array.
I also had same issue. I had bit complex object that I was pushing in to the array. What I did; I Convert JSON object as String using JSON.stringify() and push in to the Array.
When it is returning from the array I just convert that String to JSON object using JSON.parse().
This is working fine for me though it is bit far more round solution.
Post here If you guys having alternative options
I do not know why a JSON way of doing this has not been suggested yet.
You can first stringify the object and then parse it again to get a copy of the object.
let uniqueArr = [];
let referencesArr = [];
let obj = {a: 1, b:2};
uniqueArr.push(JSON.parse(JSON.stringify(obj)));
referencesArr.push(obj);
obj.a = 3;
obj.c = 5;
uniqueArr.push(JSON.parse(JSON.stringify(obj)));
referencesArr.push(obj);
//You can see the differences in the console logs
console.log(uniqueArr);
console.log(referencesArr);
This solution also work on the object containing nested keys.
Before pushing, stringify the obj by
JSON.stringify(obj)
And when you are using, parse by
JSON.parse(obj);
As mentioned multiple times above, the easiest way of doing this would be making it a string and converting it back to JSON Object.
this.<JSONObjectArray>.push(JSON.parse(JSON.stringify(<JSONObject>)));
Works like a charm.

Categories

Resources