Retrieve JSON information utilizing a specific value stored in the localStorage

After an extensive search online yielded no results, I decided to seek assistance here.

This is what I have managed to gather so far:

  • JSON

I possess a JSON file containing various lists of words that require retrieval based on user input. The structure appears as follows:

{
    "length": 10,
    "targetWords": {
        "SOME_NAME": [
            {
                "words": [
               "xyz",
                "xyz",
                "xyz",
                "xyz",
                "xyz",
                "xyz",
                "xyz",
                "xyz",
                "xyz",
                "xyz"
                ]
            },
            {
                "text": "Some example text",
                "letter": "X",
            }
        ],
}
  • localStorage input

A prompt asks the user to select an option and stores the answer in a variable known as "userInput".

userInput = localStorage.getItem("something")
  • The JSON data is fetched and assigned to a variable (leveraging Phaser Framework)

TARGET_SOUNDS_DATA = this.game.cache.getJSON('targetSounds')

My current goal is to extract the values from within. I can achieve this by following this approach:

TARGET_SOUNDS_WORDS_ARRAY = TARGET_SOUNDS_DATA.targetWords.SOME_NAME[0].words

However, when attempting to utilize the user's response/input like so:

TARGET_SOUNDS_WORDS_ARRAY =TARGET_SOUNDS_DATA.targetWords.userInput[0].words

Only undefined is returned.

It is evident that I am making a mistake, but where?

Any form of assistance or hints would be greatly appreciated! Thank you for your time!

Best Regards, J

Answer №1

Utilize square brackets for selecting a property using a variable

ACCESS_WORDS_ARRAY = ACCESS_DATA.wordsArray[userInput][0].content

Answer №2

To retrieve the desired outcome, begin by parsing it, and subsequently accessing it based on userInput like so:

TARGET_WORDS_ARRAY = TARGET_DATA.userInput[targetWords][0].words

Answer №3

From what I gather, it seems that localStorage functions as a basic key/value storage system. In order to store JSON data, you would need to first convert it into a string format, save it in the localStorage, and then parse it back into an object when needed.

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

In case of an API error with the Nuxt fetch method, ensure that the entire site responds with a 404

Is it possible to configure a Nuxt website to respond with a 404 error when the API raises a 404 error? The API call is made on the client side using the fetch method: Check out this demo here: codesandbox demo Code Snippets index.vue <template> ...

What is the best method for toggling a class to indicate the active tab in VueJS?

My goal is to set the active class on the first <li> tab by default, and then switch it to the second <li> tab when selected. I plan to use CSS to visually indicate which tab is currently active. If you would like to see the current output, ch ...

Choosing a sequence of text snippets divided by the <br> tag found inside a specific class

Is there a way for me to extract each of those strings using jQuery or JavaScript? For example, 'fight club', 33 Main Street, Houston, etc. <span class="cart_text2"> Fight Club <br> 33 Main Street, <br> Hou ...

Struggling with parsing intricate JSON data into an object with GSON?

Through a service API call, I am receiving a JSON String with data that includes various reportRecords. For simplicity, I have included only three of these records out of the potential ~500. Here's an excerpt of the JSON response: { "aggRecords": ...

code reading json without specified key

I'm facing what seems like a simple question, but I can't seem to crack the code. I'm currently coding in Python 3.3 and have retrieved something from a JSON file that resembles this: some_list = json_response['key'] # some_list ...

SailsJS failing to detect changes in local JSON file

https://i.stack.imgur.com/RG13Y.png This sailsjs application does not utilize any database. Instead, it relies on multiple JSON files located in the data folder within the root directory. The controller accesses this data as follows: req.session.categori ...

AngularJS enhances user experience by allowing textareas to expand upon click

I am just starting to learn about angular.js and I'm wondering how to add a text area when clicking on an image. ....... ..... ..... </thead> <tbody> <tr ng-repeat="stu in Studentlist"> <td>{{stu.rollno}}</td> <td> ...

navigating through a specific section of a data chart

I need the first column of a table to stay fixed while the rest of the columns scroll horizontally. Here's the code I have: <div id="outerDiv"> <div id="innerDIv"> <table> <tr><td>1</td><t ...

Integrating Excel into a webpage - is it possible?

Currently facing an issue on my website. I'm trying to open a 'file://' URL directly with the <a href=""> element in a browser, but it's prohibited. I'm searching for a plugin or similar solution that can enable me to execut ...

Having trouble with the chaining of AJAX calls using Promises?

I am currently attempting to send a POST request (technically a DELETE) to a php page called delete_post.ajax.php. This request takes data from my AJAX call and utilizes it to delete an item from the database. After deletion, I want my AJAX to then send a ...

Issue with retrieving POST body from Ajax call in Play Framework

I am currently attempting to send a POST request to my backend using JSON data. The frontend call appears like this: function register() { var user = $("#form_reg_username").val(); var pass = $("#form_reg_password").val(); var referal = $("#form_reg ...

Incorporating React-Native components into a Next.js application within an Nx monorepository: A Step-by-Step

I'm encountering an issue while attempting to integrate React Native components into an Nx monorepo setup. Initially, the Nextjs app compiles successfully: info - Fast Refresh enabled for 1 custom loader event - client and server compiled successful ...

Sort choices based on the optgroup category label text

I want to create a system where the user can select a game from one dropdown menu and then see only the consoles that game is available on in another dropdown menu. For example, if the user selects a game like Forza Horizon which is available on multiple c ...

Learning to retrieve and implement information from a JSON document in Angular7

I'm attempting to retrieve data from a JSON file and present it in a formatted manner. Link to the JSON FILE: https://raw.githubusercontent.com/datameet/railways/master/trains.json Here is the code I'm using, but encountering an error in the fe ...

Why does app.post function while router.post does not seem to work?

I have encountered an issue while logging in with React on the front end. The process goes to my node/Express/Passport backend and I am able to successfully log in when it reaches the backend. However, I am facing difficulties in communicating that informa ...

What is the best way to resize my hamburger menu and achieve a flawlessly circular border for it?

I've been struggling to reduce the size of my hamburger menu (both height and width) for some time now. I managed to make it a bit smaller, but I can't seem to figure out how to shrink it further. Additionally, I'm having trouble creating a ...

Transformation of JSON data into a structured dataframe

Investigating club participation by analyzing data retrieved as JSON through a URL request. The JSON obtained and loaded using json_loads is presented below: df = [{"club_id":"1234", "sum_totalparticipation":227, "level&q ...

JavaScript can retrieve the default page name that is hidden within the browser's URL

When a URL is entered without a specific file name at the end, such as "www.google.com," the server typically serves a default file like "index.html" or "default.aspx." In this scenario, if the browser displays "www.google.com," I am looking to extract the ...

Having trouble getting web components registered when testing Lit Element (lit-element) with @web/test-runner and @open-wc/testing-helpers?

Currently, I am working with Lit Element and Typescript for my project. Here are the dependencies for my tests: "@esm-bundle/chai": "^4.3.4-fix.0", "@open-wc/chai-dom-equals": "^0.12.36", "@open-wc/testing-help ...

I encountered an issue with the "props map error" while working on this

Hello everyone, I am currently in the process of learning React by creating a toggle button for switching between light and dark modes. However, I have encountered an issue when attempting to map through the state and display the data in card format (altho ...