JavaScript / JavaScript Local Storage and Session Storage

Storing Complex Data Structures

This tutorial focuses on storing complex data structures, such as arrays and objects, in Local and Session Storage. You will learn how to convert these data types to strings for s…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Teaches how to work with local storage and session storage for data persistence.

1. Introduction

This tutorial is designed to help you understand how to store complex data structures like arrays and objects in Local and Session Storage. In JavaScript, only strings can be stored in Local and Session Storage. Therefore, we'll cover how to convert these complex data types into strings for storage, and then convert them back to their original form when we need to use them.

By the end of this tutorial, you will be able to:

  • Understand what is local and session storage
  • Store complex data structures in local and session storage
  • Retrieve and use stored data

Prerequisites: Basic understanding of JavaScript, including data types, arrays and objects.

2. Step-by-Step Guide

Local and Session Storage are part of the Web Storage API. They provide a way to store key-value pairs in a web browser. The main difference between them is that Local Storage data has no expiration time, while Session Storage data gets cleared when the page session ends.

Storing Complex Data Structures

Since Local and Session Storage can only store strings, we need to convert our complex data structures into strings. This can be done using the JSON.stringify() method.

Retrieving Stored Data

To retrieve our data, we use the JSON.parse() method to convert our data back into its original form.

3. Code Examples

Example 1: Storing an array

let fruits = ["apple", "banana", "cherry"];
//convert the array into a string
let fruitsString = JSON.stringify(fruits);
//store it in local storage
localStorage.setItem("fruits", fruitsString);

In the code above, we first define an array of fruits. We then convert this array into a string using JSON.stringify(). Finally, we store this string in Local Storage using localStorage.setItem().

Example 2: Retrieving an array

//get the string from local storage
let fruitsString = localStorage.getItem("fruits");
//convert it back into an array
let fruits = JSON.parse(fruitsString);
console.log(fruits); // ["apple", "banana", "cherry"]

Here, we retrieve the stored string from Local Storage using localStorage.getItem(). We then convert this string back into an array using JSON.parse().

4. Summary

In this tutorial, we learned how to store complex data structures in Local and Session Storage. We did this by converting our data into strings using JSON.stringify() before storing, and converting them back into their original form using JSON.parse() after retrieving.

For further study, consider exploring how to handle errors when using JSON.parse() and JSON.stringify(), and how to check if a particular key exists in storage.

5. Practice Exercises

  1. Store an object in Local Storage, retrieve it, and log it to the console.

  2. Create a shopping cart array with items as objects. Each item should have a name and price. Store the shopping cart array in Session Storage.

Solutions:

let user = {name: "John", age: 30};
let userString = JSON.stringify(user);
localStorage.setItem("user", userString);

let retrievedUserString = localStorage.getItem("user");
let retrievedUser = JSON.parse(retrievedUserString);
console.log(retrievedUser); // {name: "John", age: 30}
let cart = [
  {name: "apple", price: 1},
  {name: "banana", price: 2},
  {name: "cherry", price: 3}
];
let cartString = JSON.stringify(cart);
sessionStorage.setItem("cart", cartString);

Remember, practice is key to mastering these concepts. Keep experimenting with different types of data structures.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Random Name Generator

Generate realistic names with customizable options.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Favicon Generator

Create favicons from images.

Use tool

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help