Get object from Local Storage Angular 8 - javascript

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

Related

how do I update a single value of an item in session storage

I have a SessionStorage item set with the following values:
key : state-allRequestsandResponses
value : "{"first":30,"rows":10,"sortField":"isWorkComplete","sortOrder":1}"
I want to obtain the value for first for example and change the value of 30 to say 40.
I'm having real difficulty with using sessionStorage.setItem to change this value. Can anybody give an example of how to change this value.
You can try below method in order to store, get the data and update
let data = {"first":30,"rows":10,"sortField":"isWorkComplete","sortOrder":1}
//storing the data for the first time
sessionStorage.setItem("state-allRequestsandResponses", JSON.stringify(data));
In order to update the data in sessionStorage get the object and parse it as json object since sessionStorage will store the data as strings.
//Get the object and parse it
data = JSON.parse(sessionStorage.getItem("state-allRequestsandResponses"))
data.first = 40;
sessionStorage.setItem("state-allRequestsandResponses", JSON.stringify(data));
//Verify whether the data updated in sessionStorage
console.log(sessionStorage.getItem("state-allRequestsandResponses"))
Once we get the value from sessionStorage, we need convert it into JSON in order to use it as a normal object.
try to do some changes like below..
const modifiedValue = JSON.parse(sessionStorage.getItem('state-allRequestsandResponses'));
modifiedValue.first(40);
sessionStorage.setItem('state-allRequestsandResponses', JSON.stringify(modifiedValue));
Hope this helps.. :)

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]))
}

Saving more data to local storage

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

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.

accessing values form string in jquery

I am returning string from database in following
format =opRadio=1&selSchool=0&opRadio2=1&selClg=0
What I want to access values like 1 or 0 in javascript or jQuery. I mean I want to retrieve 1 when I pass opRadio.
I tried by encoding string into json but no luck.
Thanks in advance.
Try this :You can use split('&') to seperate key value pair and then use split('=') to get key and value to put it in map. use map to retrieve values by passing key
var dbString = "opRadio=1&selSchool=0&opRadio2=1&selClg=0";
dbString = dbString.split('&');
var map = {};
for(var i=0;i<dbString.length;i++)
{
var keyValue = dbString[i].split('=');
map[keyValue[0]] = keyValue[1];
}
//to read value by passing key
alert(map['opRadio']);

Categories