Saving more data to local storage - javascript

I know it is best way to use JSON but it is too complex for me to understand. Thus, may i ask is there any other ways to make sure that my data does not overwrite in local storage. Example using for loop or using another key name. Please help me by giving my examples as i am very new to HTML/JavaScript.
function saveToLS(){
var Name = document.getElementById("rName");
var namesaved = Name.value;
localStorage.setItem("Name",namesaved);
var Comment = document.getElementById("rComment");
var commentsaved = Comment.value;
localStorage.setItem("Comment",commentsaved);
}

Are you going to store multiples of these? You should store them in an array or object (for example adding a timestamp id field) and store that array in LS.

Yeah..Me Also new In this Part... but I hope to you help full this code please try It..
var key = 0;
for(key;key<10;key++){
localStorage.setItem(key, localStorage.getItem(key) + "Datas");
}

The best option is using JSON. JSON is not very complex. It's just a string which is a result of stringification of a language construct like an array or object.
What you need is an array: [], stringified version of it: "[]". So you need to push an element into the array. How? Convert the stored JSON string into an array by parsing it, and then push an element and stringify the new array. Here is an example:
var names = localStorage.getItem("Name");
names = names ? JSON.parse(names) : [];
names.push('newName');
localStorage.setItem("Name", JSON.stringify(names));
Also don't use 2 keys for storing 2 datum that belongs to one item. It will be hard to maintain. Use an object, an array of objects:
comments.push({
author: 'name of the author',
comment: 'here goes the comment body...'
})

function saveToLS(){
var Name = document.getElementById("rName");
var namesaved = Name.value;
if(localStorage.setItem("Name").length){ //the data already exists
// Do whatever if the data already Exists......
}else{
localStorage.setItem("Name",namesaved);
}
var Comment = document.getElementById("rComment");
var commentsaved = Comment.value;
if(localStorage.setItem("Comment").length){ //the data already exists
// Do whatever if the data already Exists......
}else{
localStorage.setItem("Comment",commentsaved);
}
}
check using localStorage.getItem(), if the data already exists and if its true don't write the data again or for that matter do whatever you want like save the data with another key
if(localStorage.setItem("Name").length){ //the data already exists
localStorage.setItem("SomethingElse...",namesaved); //something else
}else{
localStorage.setItem("Name",namesaved);
}

Related

Get object from Local Storage Angular 8

I have a localstorage which is storing some data. I am trying to get the data in a component using localStorage.getItem('id'); but it is undefined. The problem is, localStorage is storing id in a strange format. It is stored like abcabcabc.id Now there are multiple such parameters in localStorage and for each logged in user the string abcabcabc changes. How can I still get id value. Can I compare string or something to get values? Like if it contains string .id only read that value? If yes, can you explain how would that be achieved?
localstorage:
abcabcabc.username.id = sdfsdfsdfs
abcabcabc.username.refreshToken = sdfsdfs
abcabcabc.username.accessToken = ertsdffdg
Since you do not know the exact key stored in localStorage fetch all of them and then iterate over it. Next, match part of the key that you know i.e id as illustrated below:
// fetch all key-value pairs from local storage
const localStorageKeys = { ...localStorage };
// iterate over them
for (const index in localStorageKeys) {
// see if key contains id
if (index.includes('id')) {
// fetch value for corresponding key
console.log(localStorageKeys[index]);
}
}
localStorage sets data as a map of key-value pairs, so :
var id = {key:"id", value:"sdfsdfsdfs"}
//JSON.stringify converts the JavaScript object id into a string
localStorage.setItem('id', JSON.stringify(id));
now you get the data by:
var getTheId = localStorage.getItem('id');
//you can use JSON.parse() if you need to print it
console.log('getTheId: ', JSON.parse(getTheId));
This is how you would normally do it, but since I don't know how you had set the data, you would instead get the data by:
var x = localStorage.getItem(id);//normally getting your id
//parse it
var st = JSON.parse(x);
var ids = [];
while(st.includes(id)){
//this is to only get the abcabacabc
var newId = st.substring(0,9);
ids.push(newId);
}
console.log(ids);

How to add JavaScript array into localStorage for temporary data store?

I want to add my array data into localStorage so that when I enter data into a questions array my data should be there after refreshing the web page. Actually, I want to push questions array and store data into an array. Below code, I have tried but it's not working properly. Can anybody help me, please?
//add newly entered data into questions using localStorage.
if(localStorage.getItem('setQuestions') == null){
var questions =[];
}else{
questions = JSON.parse(localStorage.getItem('setQuestions'));
}
First I should say localstorage is a key-value database; so you have to stringify your array by using JSON.stringify(questions); to convert an object/array to string;
It's very easily to add a string to localstorage :
localstorage.setItem("questions", JSON.stringify(questions));
But I recommend you to use WebSQL or IndexedDb
Just add data to an array, put it in the form of string via JSON.stringify(questionss) and then parse it. Then loop over it to get values.
if (localStorage.getItem('setQuestions') == null) {
let questionss = [{
question: "Why the grass is green?",
answer: "Because of cholorophyll",
}, {
question: "What's the fastest made object on earth?",
answer: "A man hole cover"
}];
localStorage.setItem("setQuestions", JSON.stringify(questionss));
} else {
let questions = localStorage.getItem('setQuestions');
JSON.parse(questions).forEach((val, index) => alert(val.question + " " + val.answer));
}
Check this js fiddle
Ok. Actually, you didn't show us where you stored the data prior to browser refresh. Your data don't get stored automatically :)
😂
//As soon as you get your question array, do the following
var dataToStore = JSON.stringify(yourArray);
localStorage.setItem('setQuestions', dataToStore);
//And when you're back from movie and wish to continue, then do...
var questions = [];
var storedData = localStorage.getItem('setQuestions');
//Check if it was saved...
if(storedData) {
questions = JSON.parse(storedData);
}
//You have the same array data that was stored. Now, call your girlfriend and tell her you just won a lotto. 8)
//Additionally, you mentioned `push` somewhere...
//If you need to add new questions to the old one, just do...
var extendedQuestions = questions.concat(newQuestions);/*newQuestions must be an array*/
/*
//add newly entered data into questions using localStorage.
if(localStorage.getItem('setQuestions') == null){
var questions =[];
}else{
questions = JSON.parse(localStorage.getItem('setQuestions'));
}
*/
NOTE
There's no real deal in asking someone to write your code for you or writing someone's code for them. We should learn how to do it on our own.
localstorage accepts strings so simply JSON.stringify prior to storing and JSON.parse to read that string into an array object.

What query can i use to fetch data from local storage of selected key value

I need to store a lot of data in local storage for my app. I am successful in storing that. Now i need to fetch data in an array but of the selected key/values and not all or just 1 of them. I have named these key as "section"+id as seen below, need to select these in an array.
localStorage.getItem(key) will return the data for the key you provide. Data from localStorage is serialized so you need to parse it with JSON.parse(data) into a plain JS object and then you can work with it as any other object.
You can only get a single item with localStorage.getItem so if you want to get multiple items in an array you'll have to loop and get each one individually and put them in an array.
Maybe something like this:
var keys = Object.keys(localStorage).filter(function(key) {
return /^section\d+$/.test(key);
});
var dataArray = keys.map(function(key) {
return JSON.parse(localStorage.getItem(key));
});
First, we get all the "section###" keys with the filter function. Then we create a new array with the data for each corresponding item using the map function.
Try this code. I have edited it.
var keys = [];
var data = [];
for (var key in localStorage) {
if (key.indexOf("section") > -1)
keys.push(key);
}
for (var i in keys) {
data.push(localStorage.getItem(keys[i]))
}

Parse the JSON Object with Index or position instead of keyname using Jquery?

My Existing Code and Explanation
Working Fine, But I want to Create a template like Its should read JSON Data that Having keys in any name, I am Always reading data from JSON object in 2nd Position
Now I read the JSON that passed in the argument (data) inside that using the for loop extract single object in group, after that get the data using key(Module_Name).. I know the key(Module_Name) is always present in second position only, Now its Working Fine with keyname rather i want to fetch the data using position, that also used as template in my other modules
/* render Screen Objects */
screenRenderer.displayScreens = function(data)
{
screenRenderer.renderLayout(function(cont, boo)
{
if (boo)
{
for(i=0;i<data.length;i++)
{
var buttons = "<button class='screen_button'>"+data[i].Module_Name+"</button>";
$("#screen-cont").append(buttons);
}
}
else
{
scr_cont.show();
}
})
}
This is My Requirement, kindly awaiting suggestions, answers..
Thanks in Advance
You can use the function Object.keys(obj) to get all keys of an object as array, which you can access with an Index and than use the String you get to access the property.
So it could look like this:
var obj = data[i];
var keys = Object.keys(obj);
var result = obj[keys[1]];
Hope this is what you want.

How to store value from local storage in an array, JavaScript?

I have been trying to code in javascript where I want input given to be displayed on screen. I want to store the data from input in LocalStorage. I tried to take the value and using localStorage.setItem and localStorage.getItem I stored in local storage too. But as I want to display all the records I have inserted every time submit button has been clicked, I want to store current and previous records too.
I tried to push into an array but it had only current records and not previously stored values. I don't want jquery. I just want simple javascript code.
thank you.
eg-
var data=[];
function myFunction(data)
{
var name= document.getElementById("nm").value;
localStorage.name= name;
for(var i=0;i<localStorage.length;i++)
{
var key = localStorage.key(i);
var value = localStorage.getItem(key);
data.push( value);
}
}
Yep, as mentioned in the comments it is best to just store the String representation of your array and store it as a value in localstorage. Web localstorage lets you store simple key value pairs which can be integers or strings (mostly strings) official docs
You could do something like this:
var name= document.getElementById("nm").value;
var data;
if (localStorage.getItem("name") === null)
//First value to be stored
data = [];
else
//There is some value already in the array
data = JSON.parse(localStorage.getItem("name"));
//Push name to data array in any case
data.push(name);
//Update localStorage
localStorage.setItem("name",JSON.stringify(data));
I hope this gets you started in the right direction.

Categories