What is the best way to incorporate a fresh array into the existing array element stored in local storage?

I stored a group of users in the local storage:

let btnSignUp = document.getElementById("btnSignUp");
btnSignUp.addEventListener('click', (e) => {
  let existingUsers = JSON.parse(localStorage.getItem("allUsers"));
  if (existingUsers == null) existingUsers = [];

  let userLogin = document.getElementById('authLogin').value;
  let userEmail = document.getElementById('authEmail').value;
  let userPassword = document.getElementById('authPassword').value;
  let userConfirmPassword = document.getElementById('authConfirmPassword').value;
  if (userPassword == userConfirmPassword) {
    let users = {
      "login": userLogin,
      "email": userEmail,
      "password": userPassword,
      "contacts": []
    };
    localStorage.setItem("users", JSON.stringify(users));
    // Save allEntries back to local storage
    existingUsers.push(users);
    localStorage.setItem("allUsers", JSON.stringify(existingUsers));
  } else {
    alert("Password and confirm password must be the same");
  }
}, false);

Now, I am looking to create an array of contacts for the chosen user. A contact structure should include the following information:

let userSurname = document.getElementById('_surname').value;
let userName = document.getElementById('_name').value;
let userCountry = document.getElementById('_country').value;
let userCity = document.getElementById('_city').value;
let userEmail = document.getElementById('_email').value;
let userPhone = document.getElementById('_phone').value;
let userWorkPlace = document.getElementById('_workPlace').value;

let contact = {
  "surname": userSurname,
  "name": userName,
  "country": userCountry,
  "city": userCity,
  "email": userEmail,
  "phone": userPhone,
  "workPlace": userWorkPlace
};
localStorage.setItem("contact", JSON.stringify(contact));

Please provide guidance on how to achieve this.

Answer №1

Develop an array containing contact objects and use JSON.stringify to convert it into a string.

 let contacts = [];
 let contactObj = {
  "surname": userSurname,
  "name": userName,
  "country": userCountry,
  "city": userCity,
  "email": userEmail,
  "phone": userPhone,
  "workPlace": userWorkPlace
};
contacts.push(contactObj)
localStorage.setItem("contact", JSON.stringify(contacts));

Answer №2

If you find yourself constantly de-serializing and serializing the contacts list of a specific user, you can utilize the following pair of functions to store contacts in local storage. While it may not be a flawless solution, it does address your concern. Feel free to customize and enhance this solution according to your needs.

To Store Contacts

function saveContact(username, contact){
    let count = localStorage.getItem(username+"-contacts-count") || 0;
    contact.index = count;
    localStorage.setItem(username+'-contact-'+(count++), JSON.stringify(contact));
    localStorage.setItem(username+"-contacts-count", count);
}

To Fetch Contacts

function retrieveContacts(username){
    let count = localStorage.getItem(username+"-contacts-count") || 0;
    let contacts = [];
    for(let i = 0; i < count; i++){
        let contact = localStorage.getItem(username+'-contact-'+(i));
        if(contact){
            contacts.push(JSON.parse(contact));
        }
    }
    return contacts;
}

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

Creating a visually dynamic stack of images using javascript, jquery, and HTML

I'm interested in creating a unique image viewer using javascript/jQuery/HTML that combines elements of a book page flip and iTunes coverflow, optimized for mobile device browsers. I've been searching for tutorials to help kickstart this project, ...

Can someone explain the function of statements such as (function () { // code; }.call(this)); within a JavaScript module?

By utilizing the Function.prototype.call() method, it becomes possible to create a function that can be applied to various objects. I delved into the code of , which had been minified and required to be un-minified for examination. The structure of the co ...

Using JAX-RS to serve excel files in webservice after an ajax call - tips on displaying the save dialog

I am facing an issue with a JAX-RS webservice that generates an excel file as a byte array and sends it back to my javascript application. Despite setting the necessary headers, there is no save dialog popping up as expected. I have verified the response u ...

Submitting form by double clicking and pressing enter at the same time

When using jQuery Validate to validate forms, I encounter a problem where double-clicking the submit button results in my application making two entries with the same data. This issue also occurs when pressing enter multiple times. Despite researching dif ...

Guide to utilizing font awesome 5 after installation through NPM

After successfully installing font-awesome in my project using npm, I am unable to locate the documentation on what steps to take next: $ npm install --save @fortawesome/fontawesome-free-webfonts My question now is: what should I do after this? Could so ...

How can I retrieve child divs from a cloned div object using jQuery?

I begin by executing this code to obtain a clone of my data var cloned = $(".hoverer:first").clone().attr({id: 'id_'+itm_id, class: 'hoverer-active'}); The main div contains another div with its own id and class, and within that div t ...

Steer clear of duplicating patterns in vue templates

I have a significant issue with a component that needs to be repeated multiple times in the parent template due to the usage of v-if. The component code is as follows: <SelectCard v-for="(channel, index) in category.visibleChannels" :key="index + & ...

Calling @Url.Action multiple times does not consistently return the same results

It appears that there is a discrepancy related to jQuery/MVC3 that I have yet to figure out. If anyone could shed light on this matter, it would be greatly appreciated. Whenever I invoke an action routine multiple times, the @Url.Action routine generates ...

Tips for successfully retrieving a boolean value from an ASP.Net JavaScript AJAX request using a C# method

Query: Is there a way to call a C# function from JavaScript code on an .aspx webpage to get authentication results based on a username and password? Here is the JavaScript AJAX POST request I am currently using: $.ajax({ type: "POST", ...

A different approach to calling JavaScript functions

I have a method that populates an array. I would like to utilize it in this manner: arrayname.fill("First Array"); And not like this: arrayname = fill("First Array"); What approach should I take? function fillArray(name) { let newArray = ...

Should a Service Worker be automatically installed on each page reload, or only when a user navigates to a new page?

Currently in the process of developing a PWA. I have encountered an issue where the service worker seems to be installing on every page reload or when navigating to a different page within my app. It appears that many files are being cached during the inst ...

The POST variable comes up empty when making an AJAX request

I am currently attempting to utilize an AJAX call to POST the selected value from a dropdown list. However, I am encountering an issue where the POST variable is coming back empty once a value is chosen from the dropdown. In order to troubleshoot this pro ...

Is there a way to set up automatic switching to a minimized browser window when receiving an alert, even if you are currently using a different window like Outlook or Explorer?

Is there a way to automatically switch to a minimized browser window from a different program window (such as Outlook or Explorer) when an alert is received on a specific tab? I'm looking for a Javascript/Jquery solution. I've attempted the foll ...

Can a relative link with parameters but no path be used?

Can I omit the path from an href tag and begin with a question mark instead? For instance, if my website is https://example.com/mycgi, would it be acceptable to have a link like this: <a href="?foo=bar">bar</a>? I tested this on Fir ...

Testing React components with Jest by mocking unnecessary components

Consider a scenario where we have the Page component defined as: const Page = () => <> <Topbar /> <Drawer /> <Content /> </> When writing an integration test to check interactions within the Drawer and Con ...

How to efficiently calculate totals in an HTML table using JavaScript/jQuery

I have a gridview that displays product details and includes a quantity textbox that is not linked to any database. For each row, I want it to show the cost (price * quantity) and the total cost for all rows in a label below. However, I am encountering a f ...

Create a list using ReactJS

I've been working on rendering a dynamic list in JSX, but I'm facing issues displaying the items. Below is my code snippet where I attempted to use useState const [orderList, setOrderList] = useState([]) and setOrderList(prev => [...prev, chil ...

What's the deal with this route being a 404 error?

I'm currently working on incorporating a new route into Express, specifically for handling 404 errors. Despite my efforts to configure the route in a similar manner to others, I am encountering some difficulties. var repomapRouter = require('./ ...

Storing toggle open state using a variable

I have created a toggle open/close DIV with a UL list inside that looks like this: <div id="dropdown-1"> <div class="option-heading"> <i class="fa fa-angle-double-up"></i> <i class ...

The click event fails to trigger while trying to parse external HTML

Currently, I am working on a project that requires me to load HTML from an external file and insert it into an existing div element. Although the process is successful overall, I have encountered an issue where the .click() events do not trigger when click ...