When the localStorage is empty, populate it with data from a JSON file

const username = document.querySelector("span.username").textContent;

if (localStorage.getItem(username) === null) {
    //user data not found, start setting
    //localStorage.setItem(username, JSON.stringify(userA));
    console.log("localstorage for " + username + " is not found");
    $.getJSON("./php/settings.json", function(json) {
        console.log(json[username]);
        userA = json[username];
        localStorage.setItem(username, JSON.stringify(userA));
    });
}

My data is structured as follows in my /settings.json file. (by the way, console.log(json[username]); displays the data correctly when the code snippet is copied and pasted into the developer console).

./settings.json

{"sarah":{"userCData":[{"id":"slz1","checked":"false"},{"id":"slz2",...................]}}
{"albert":{"userCData":[{"id":"slz1","checked":"false"},{"id":"slz2",...................]}}
{"sally":{"userCData":[{"id":"slz1","checked":"false"},{"id":"slz2",...................]}}
{"petey":{"userCData":[{"id":"slz1","checked":"false"},{"id":"slz2",...................]}}
{"gilbert":{"userCData":[{"id":"slz1","checked":"false"},{"id":"slz2",...................]}}

What am I missing here? The intention is to fetch from my json file if the user's data in localstorage is not found.

Answer №1

If you're wondering how to retrieve an object's index using a variable, you can achieve that by using the square bracket [] selector. Here's an example:


data[propertyName]

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

Is it possible to arrange JSON Objects vertically on a webpage using tables, flexboxes, divs, and Javascript?

Within my JSON data, I have multiple products defined. My goal is to loop through this JSON and display these products side by side on a web page for easy comparison. Initially, I envision structuring them in columns and then rows: https://i.sstatic.net/K ...

`Why is it important to debug javascript code?`

I have some outdated JavaScript code that surprisingly still works in Internet Explorer from 2000-2002, but refuses to function properly in browsers like Firefox, Chrome, and Opera. I've come across various browser quirks where different browsers inte ...

Is there an isPrime function specifically designed for a number generated from an array of integers?

I am looking to develop an isPrime method for a number that is constructed from an array of integers. The array contains 25 integers, filled from the end, resulting in a number like 13512 represented as {0,0,0,0,0,...0,0,1,3,5,1,2}. My objective is to de ...

How to Use Express.js to Stream Assets (JS/CSS/images) from Amazon S3

After successfully launching my Node.js blog on AppFog, I have the idea of utilizing an Amazon S3 bucket to host and stream all my assets such as javascript, stylesheets, and images. I am now wondering how I can configure Express.js to properly serve thes ...

Gathering data from distant servers through powershell

I need to retrieve drive information from a collection of Windows servers running between 2008 and 2016 using PowerShell. I have successfully written code to fetch the information locally, but I am struggling to do it remotely or from a text file containin ...

How to stop empty numbers in angular.js

My goal is to ensure that an input with a required attribute always has some value, and if left empty, defaults to zero. <input ng-model='someModel' required> I have created the following directive: App.directive('input', fun ...

The interaction between jQuery and Rails through ajax calls

Attempting to work with basic functionality, Sending a request with data and receiving a response with data, then displaying it using jQuery and Rails This piece of code pertains to the frontend. $("#internal_btn").click(function() { //windo ...

The powerful combination of Newtonsoft JSON and Graph API

Utilizing Newtonsoft JSON, I deserialize responses from the Facebook Graph API. For instance, when parsing user posts, the response looks like this: data": [ { "story": "", "created_time": "", "id": "" }] To handle this data, I ...

I'm experiencing an issue with res.redirect() as it is not directing me to the expected page. Despite no errors being shown, I am left wondering what

Despite everything working as expected, I am facing an issue with redirecting the user to a different URL after they send a message. I have tried using res.redirect from the server side in response to an AJAX POST request, but it seems like I am still on t ...

Customer Notification System Malfunctioning on Front End

I am currently experimenting with MeteorJS technology and attempting to use alerts for success or failure notifications when making a meteor call. However, I've encountered an issue where the alerts are not functioning as expected. T ...

Looking for a demonstration using dust.js or handlebars.js in a two-page format with express3.x and node?

Currently, I am in the process of selecting a templating engine to use. While I have come across numerous single-page examples utilizing template engines, I am specifically searching for a practical example that demonstrates handling two distinct pages whi ...

Convert Laravel error messages to JSON format for API responses

I am working on developing an API using Laravel and I need to adjust the default error messages into JSON responses. Currently, when an error occurs, I receive the following response: { "email": [ "The email has already been taken." ], ...

The controller is unable to retrieve the posted value

Whenever I try to retrieve the post value from my controller, it always returns null. Even though I can see that there is a post value present when I check, for some reason, I am not able to access that value in my controller. Does anyone know what the p ...

Tips for activating a deactivated input field in ReactJS

I am trying to create a feature where my textfields are automatically disabled, but can be enabled for editing by clicking an 'Edit' button. Clicking the button again should disable the textfields and save any edits made. I have experimented with ...

Issue with ng-repeat rendering on screen

Creating a breadcrumb has been my latest project, so I decided to develop a service specifically for this purpose. In order to display all the breadcrumbs, I utilized an ng-repeat in my HTML. Additionally, I set up an event listener for '$routeChange ...

Spontaneous visual paired with text upon refreshing

I am new to Java script and I am working on creating a web page that displays two random numbers every time it is refreshed. Depending on these numbers, specific text should be shown. These numbers are represented by images ranging from 0 to 5. Currently ...

Retrieving information from a JSON array

I received the following output from a JSON call in C#: {"Field": [ "PID", "PName"], "Data": [ [ 5, "A3"] ] } I am looking to extract only the Data part, which is an array of data, and store it in a DataTable. I need to do t ...

Steer clear of manually inputting URLs in your React components

As I embark on my journey with Gatsby, I am noticing a recurring pattern in my code. A prime example is when creating links, where I often find myself doing something like this: import {kebabCase} from "lodash"; // ... <Link to={`tags/${kebabCase( ...

Looking for a way to retrieve JSON data from an HTML page using JavaScript? Look no further

There is a page that sends me JSON data. You can make the request using the GET method: or using the POST method: argument --> unique_id=56d7fa82eddce6.56824464 I am attempting to retrieve this information within my mobile application created with I ...

Javascript code experiences a shift in two different styles within a single conditional statement

I'm new to web design and I'm having trouble getting this code to work properly. Can anyone help me fix it so that both styles are applied correctly? // Access the sign_up modal window var modal = document.getElementById('id01'); // A ...