Bitly
Bitly

Reputation: 948

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

Upvotes: 0

Views: 3562

Answers (2)

Nicholas K
Nicholas K

Reputation: 15423

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

  }
}

Upvotes: 1

Ferdinand
Ferdinand

Reputation: 511

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

Upvotes: 0

Related Questions