Fetching an item from Local Storage in Angular 8

In my local storage, I have some data stored in a unique format. When I try to retrieve the data using localStorage.getItem('id');, it returns undefined. The issue lies in the way the data is stored within localStorage - it's structured as abcabcabc.id. This unique identifier part ("abcabcabc") changes for each user session. Despite this challenge, I need to find a way to extract the value of id. Is there a method to compare strings and isolate only those that contain ".id" for retrieval? If so, could you provide an explanation on how this can be accomplished?

Data stored in localStorage:

abcabcabc.username.id = sdfsdfsdfs
abcabcabc.username.refreshToken = sdfsdfs
abcabcabc.username.accessToken = ertsdffdg

Answer №1

To retrieve a specific key from localStorage when the exact key is unknown, one can fetch all keys and then loop through them to find the desired key. In the code snippet below, we demonstrate how to extract the value of a key containing 'id' in its name:

// Accessing all key-value pairs stored in local storage
const allKeys = { ...localStorage };

// Looping through each key
for (const keyIndex in allKeys) {

  // Checking if the key contains 'id'
  if (keyIndex.includes('id')) {

    // Retrieving the value for the corresponding key
    console.log(allKeys[keyIndex]);

  }
}

Answer №2

When using localStorage, data is stored as key-value pairs. Here's an example:

var id = {key:"id", value:"sdfsdfsdfs"}
//JSON.stringify converts the JavaScript object id into a string 
localStorage.setItem('id', JSON.stringify(id));

To retrieve the data:

var getTheId = localStorage.getItem('id');
//If needed, use JSON.parse()
console.log('getTheId: ', JSON.parse(getTheId));

This is how you typically access the data. However, if you are unsure about how the data was initially set, you can follow these steps instead:

var x = localStorage.getItem(id);
//Parse the data
var st = JSON.parse(x);
var ids = [];
while(st.includes(id)){
//Extracting the specific substring 'abcabacabc'
var newId = st.substring(0,9);
ids.push(newId);
}
console.log(ids);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating through JSON data in an Angular application

I am currently facing an issue with uploading and parsing a JSON file in my Angular application. The problem lies in the fact that even though I can successfully upload the file, I am unable to access the data from it. To ensure the correct file is being ...

Is it possible to utilize jQuery's .wrap or .wrapInner to encase a variety of elements within them?

I am working with a HTML structure that looks like this: <section> <item> <ele class="blue" /> <ele class="green" /> <ele class="red" /> </item> <item> <ele class="blue" /> <ele ...

What's causing this sluggish performance?

I'm in the process of developing a Google Chrome extension and I can't help but wonder why window.onload = loadPage; function loadPage() { document.getElementById('nav-robux-amount').innerHTML = '0'; console.log(" ...

Ways to avoid using a specific type in TypeScript

Imagine having a class that wraps around a value like this: class Data<T> { constructor(public val: T){} set(newVal: T) { this.val = newVal; } } const a = new Data('hello'); a.set('world'); // typeof a --> Primitiv ...

Transform a C# DateTime object into a JavaScript date format

In my Javascript function, I am handling a C# DateTime received from MVC. If the date is null, it should return "-", and if it's a valid date, it should be returned in the formatted date. IMPORTANT: The date must be sent in the specified format from ...

Unable to successfully import { next } from the 'express' module using Typescript

Having some trouble with this line of code: import {response, request, next} from 'express' The typescript compiler in vscode is giving me the following error: Module '"express"' has no exported member 'next'. Up ...

Retrieve a specific JSON object by ID in an Angular Typescript observable

Below is a json string that contains both "stocks" and "contacts" data arrays. Depending on the request, I need to extract either the "stocks" or "contacts" data: [{ "id": "stocks", "name": "Stocks", "data": [ { "id": 1, "name": "Act ...

How can I track the number of correct answers in a ReactJS quiz with an auto-submit feature and a timer that stops?

The auto-submit feature is not functioning correctly. Although the code works fine when I manually submit the quiz at the end, if the time runs out, the score will always be 0/3 which is incorrect. // React and Material-UI imports omitted for brevity // ...

Arranging elements based on specific coordinates

const renderTimeSlots = () => { const timeSlots = []; for (let i = parseInt(workStartsAt); i <= parseInt(workEndsAt); i++) { if (i !== 0) { timeSlots.push( <div className="flex flex-row cursor-pointer"> ...

Route parameter in JavaScript: only accept numerical values

Is it possible to restrict parameter types to only accept digits? If a letter or other character is inputted, I want to fallback to a default scenario. Below are the two attempts I've made. app.get('/multi/:num?', function (request, respons ...

Steps for removing an element from an array using Mongoose and Node.js

After reading and attempting to implement the solutions provided by others, I am still struggling to understand why it's not working for me. This is my first project involving backend development. While progressing through a course, I decided to work ...

Does the rendered ID of an ASPX control always appear the same in the source HTML code?

Let's say I have an aspx textbox with id="txtkms". In the HTML view source, it appears as ContentPlaceHolder1_Gridview1_txtkms_1. I'm curious if this control will always be rendered as ContentPlaceHolder1_Gridview1_txtkms_1 every time I run my as ...

Preserving CSS styling while loading an HTML page with InnerHTML

By using the following code snippet, I have successfully implemented a feature on my website that allows me to load an HTML page into a specific div container when clicking a link in the menu. However, I encountered an issue where the background color of ...

Tips for extracting information from a website with Selenium using Python

I am currently working on a project that requires me to extract certain information using Selenium from a webpage. The elements I need are not directly visible in the page's code, indicating they may be generated by JavaScript. Here is a snippet of my ...

Filter out unnecessary attributes while utilizing an anonymous type in ClearScript

In my development project, I am creating a .NET wrapper for the popular java-script library called Linkify.js, utilizing Microsoft's ClearScript. The challenge I am facing involves implementing the attributes property within the options object parame ...

Are you transitioning from traditional scroll pagination to using ajax?

Is it possible to replace scroll pagination with ajax? I'm looking for an alternative to the large scroll pagination query and wondering if ajax could be used instead. Here is the current code snippet: feeds.scrollFeedPagination({ 'contentPage ...

Removing classes from multiple cached selectors can be achieved by using the .removeClass

Currently working on enhancing some JavaScript/jQuery code by storing selectors in variables when they are used more than once to improve performance, for example: var element = $("#element"); element.hide(); However, I am facing difficulties while tryin ...

The instantiation of generic types in Typescript

I have been working on a function that aims to create an instance of a specified type with nested properties, if applicable. This is the approach I have come up with so far. export function InitializeDefaultModelObject<T extends object> (): T { ...

Unable to resize images in Firefox

Why is it that resizing doesn't seem to work in Firefox but functions fine in Internet Explorer? I'm struggling to find a way to make it consistent across all browsers. My goal is to resize the width to 800 and height to 475, disable maximizing t ...

How can we alert users when data has been updated without the need for a page

The following code was authored by me: $('.actionButton').click(function(){ var buttonValue = $(this).val(); var userId = '<?php echo $_SESSION['id']; ?>'; console.log(userId); ...