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

Conceal the child elements underneath a selected element using jQuery

I am currently working on an order form within a website and the HTML code is structured as below: <table class="variations"> <div class="tawcvs-swatches" data-attribute_name="attribute_pa_t-shirt- one-color"> <span class="swat ...

What steps should I take to resolve the issue of my endpoint failing to accept POST requests?

I am in the process of developing a customized API, with an endpoint that is specified as shown below: https://i.stack.imgur.com/sZTI8.png To handle the functionality for this endpoint, I have set up a Profiling Controller. Inside my controller directory ...

What is the best way to change this specific JSON string into a Python dictionary?

Is there a way to transform the string below into a Python dictionary? string = [{"name":"sam"}] The end goal is to have it structured like this in Python: data = { "name" : "sam" } ...

Apply an opacity setting of 0.5 to the specific segment representing 30% of the scrollable div

I have a scrollable container for displaying messages. I would like to apply an opacity of 0.5 to the content in the top 30% of the container, as shown in this image: https://i.stack.imgur.com/NHlBN.png. However, when I tried using a background div with a ...

Using $state outside of the AngularJS environment

Currently, I am working on an AngularJS application that is meant to be a hybrid mobile app for both android and iOS platforms. Within the project, there is a JavaScript file that does not belong to any module. In this particular JavaScript file, I need to ...

Saving JSON data in a database

Is there a way to save a JSON object in my SQL database? // Let's assume $myObject is our object $json = json_encode($myObject); mysqli_query($conn, "INSERT INTO json_table (json_data) VALUES ('" . mysqli_real_escape_string($conn, $json) . "&apo ...

JavaScript functions are not being triggered when the submit button is clicked

I am facing an issue where the form buttons are not triggering functions in my React application. The post request is being made using Axios. Could this be related to the structure of my components? Or perhaps it has something to do with file naming conven ...

JavaScript code that opens a URL in a new tab with proper formatting

I'm having trouble figuring out how to make my JavaScript open a URL in a new tab. Here is the script: function viewSource(){ var webcache = "http://webcache.googleusercontent.com/search?q=cache:"; var request = "&prmd=ivn&strip=0& ...

Switch out everything except for the initial one

Can all instances be replaced except for the first one? For example, 123.45.67..89.0 should turn into 123.4567890. Edit: Specifically seeking a regex solution. I am aware of how to achieve it through concatenation or using the index. ...

A guide on reading an external JSON file using React

I'm trying to integrate an external JSON file into my React app. To demonstrate what I'm aiming for, I've provided a functional example on Codesandbox.io: https://codesandbox.io/s/morning-tdd-we2v3?file=/src/App.js Currently, the example ...

The AJAX response consistently returns a 405 status code

I am experiencing an issue with an AJAX post request. $.ajax({ type: "POST", contentType: "application/json", url: "/rating/save", data: JSON.stringify(rating), dataType: "json", mimeType: "application/json" ...

Guide on updating a specific item in a JSON array using npm request

I am currently working on setting a value in a JSON array utilizing a PUT request with the request module, specifically targeting one of multiple main objects within the array. The structure is as follows: [ 0: { status: 'pending' ...

Is it more beneficial to categorize REST-based modules/controllers by resource or by specific action/feature?

I'm facing a scenario that goes like this: Endpoint 1: Retrieve all books in the United States owned by John with a GET Request to /country/us/person/john/books Endpoint 2: Get all books owned by John in every country with a GET Request to /person/j ...

What is the best way to update the style following the mapping of an array with JavaScript?

I want to update the color of the element "tr.amount" to green if it is greater than 0. Although I attempted to implement this feature using the code below, I encountered an error: Uncaught TypeError: Cannot set properties of undefined (setting 'colo ...

Failed commitments in JavaScript without a catch block (unhandled rejection)

When working on my project in VueJs JavaScript, I want to be able to see console messages if any of my Promises are not fulfilled and do not have a catch block. I attempted using the following code: Promise.reject("error!"); window.addEventListener(&apos ...

Ensure that you do not proceed with the next step until the promise has been fulfilled

I am currently faced with a challenge in my project where I have a service that wraps a 3rd-party API to retrieve data into my controller. However, I need to perform some data processing to pivot the information before displaying it, but I am struggling to ...

Encountering an unexpected "<" error when making a post request using Postman with Rails

Here is the JSON response I am dealing with: { "vendor": { "name": "Mozelle Luettgen MD", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="06727f776b6846637e676b766a6328686372">[email protecte ...

Need help with creating a new instance in AngularJS? Unfortunately, the save method in CRUD is not getting the job done

Whenever I attempt to create a new task, nothing seems to happen and no request is being sent. What could be causing this issue? How can I go about troubleshooting it? Take a look at how it appears here Check out the $scope.add function below: var app ...

Warning: The React Router v6's Route component is unable to find the origin of the key props

I recently came across an error in my console and I'm unsure which list is causing it. Is there a way for me to trace back the origin of this error so I can pinpoint where to fix it? The error seems to be related to the React Router component, which ...

Create a layered structure using a specified path

I am aiming to create a function that can accept an object path, like { 'person.data.info.more.favorite': 'smth' } and then output a nested object: { person: { data: { info: { more: { favorite: 'smth& ...