Javascript object to localstorage

Javascript object to localstorage

December 4, 2020 — 3 min read

The localStorage API in browsers only supports adding information in a key:pair format and the key and the pair should be of type string thus native objects or arrays cannot be stored in the localStorage .

To save arrays or objects using the localStorage API in JavaScript, we need to first stringify the arrays or objects using the JSON.stringify() method, and when we need to retrieve the value we can use the JSON.parse() method.

// an object const John = < name: "John Doe", age: 23, >; 

To save this object to the localStorage First, we need to convert the John object into a JSON string. For that let’s use the JSON.stringify() method and pass the object as an argument to the method.

// an object const John = < name: "John Doe", age: 23, >; // convert object to JSON string // using JSON.stringify() const jsonObj = JSON.stringify(John); 

Now let’s use the setItem() method on the localStorage and pass the key name as the first argument to the method and the jsonObj as the second argument to the method like this,

// an object const John = < name: "John Doe", age: 23, >; // convert object to JSON string // using JSON.stringify() const jsonObj = JSON.stringify(John); // save to localStorage localStorage.setItem("John", jsonObj); 

Now to retrieve the value from the localStorage , we can use the getItem() method on the localStorage API and then convert the string to a valid object using the JSON.parse() method.

// an object const John = < name: "John Doe", age: 23, >; // convert object to JSON string // using JSON.stringify() const jsonObj = JSON.stringify(John); // save to localStorage localStorage.setItem("John", jsonObj); // get the string // from localStorage const str = localStorage.getItem("John"); // convert string to valid object const parsedObj = JSON.parse(str); console.log(parsedObj); 

Great! 🌟 We have successfully stored and retrieved from the localStorage API.

The process is the same for arrays too.

See this example using arrays,

// an array const arr = [1, 2, 3, 4, 5]; // convert array to JSON string // using JSON.stringify() const jsonArr = JSON.stringify(arr); // save to localStorage localStorage.setItem("array", jsonArr); // get the string // from localStorage const str = localStorage.getItem("array"); // convert string to valid object const parsedArr = JSON.parse(str); console.log(parsedArr); 

Источник

Javascript object to localstorage

Last updated: May 29, 2023
Reading time · 5 min

banner

# Table of Contents

# How to store an Array in localStorage using JS

To store an array, an object or an array of objects in localStorage using JavaScript:

  1. Use the JSON.stringify() method to convert the array to a JSON string.
  2. Use the localStorage.setItem() method to store the JSON string in localStorage .
Читайте также:  Php убрать после символа

Here is the minimal HTML page for the example.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> h2>bobbyhadz.comh2> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const arr = ['bobby', 'hadz', 'com']; localStorage.setItem('my-array', JSON.stringify(arr));

You can open your terminal in the same directory as the index.html and index.js files and run the following command to start a development server.

  1. Open your developer tools in Chrome by pressing F12 .
  2. Click on the Application tab and expand the Local Storage dropdown menu.
  3. You will be able to see the my-array key.

array stored in local storage

You can only store strings in localStorage , so we used the JSON.stringify method to convert the array to a JSON string.

Copied!
const arr = ['bobby', 'hadz', 'com']; // 👇️ '["bobby","hadz","com"]' console.log(JSON.stringify(arr));

The next step is to call the localStorage.setItem method to add the JSON string to localStorage .

Copied!
const arr = ['bobby', 'hadz', 'com']; localStorage.setItem('my-array', JSON.stringify(arr));

The setItem method takes the key and the value as parameters and stores the key-value pair in localStorage .

# Retrieving the stored in localStorage JSON array

To retrieve the stored in localStorage JSON array:

  1. Use the localStorage.getItem() method to retrieve the JSON string from localStorage .
  2. Use the JSON.parse() method to parse the JSON string into a native JavaScript array.
Copied!
const arr = ['bobby', 'hadz', 'com']; // 👇️ storing the array in localStorage localStorage.setItem('my-array', JSON.stringify(arr)); // 👇️ retrieving the array from localStorage const myArray = JSON.parse(localStorage.getItem('my-array')); console.log(myArray); // 👉️ ['bobby', 'hadz', 'com'] console.log(Array.isArray(myArray)); // 👉️ true

retrieve array from local storage

We used the localStorage.getItem method to retrieve the JSON string from localStorage .

The only parameter the method takes is the key.

The last step is to parse the JSON string into a native JavaScript array by using the JSON.parse method.

Let’s look at an example of how you’d render the retrieved from localStorage array.

Here is the updated HTML code.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> h2>bobbyhadz.comh2> ul id="unordered-list">ul> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const arr = ['bobby', 'hadz', 'com']; localStorage.setItem('my-array', JSON.stringify(arr)); const myArray = JSON.parse(localStorage.getItem('my-array')); console.log(myArray); // 👉️ ['bobby', 'hadz', 'com'] console.log(Array.isArray(myArray)); // true const ul = document.getElementById('unordered-list'); myArray.forEach(element => const li = document.createElement('li'); li.innerHTML = element; ul.appendChild(li); >);

render stored in localstorage array

We used the Array.forEach method to iterate over the array and created a li element for each array element.

On each iteration, we set the innerHTML property of the li element to the current array element and append each li to the unordered list.

# How to store an Object in localStorage using JavaScript

The same approach can be used to store an object in localStorage .

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> h2>bobbyhadz.comh2> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const obj = id: 1, name: 'bobby hadz', age: 30, salary: 1500, >; localStorage.setItem('my-object', JSON.stringify(obj));

If you open the Application tab in your browser’s developer tools and expand the Local Storage dropdown, you will see that the my-object key is set.

store object in local storage

As previously noted, you can only store string values in localStorage , so we used the JSON.stringify() method to convert the object to a JSON string.

To retrieve the object from localStorage :

  1. Use the localStorage.getItem() method to get the JSON string from localStorage .
  2. Use the JSON.parse() method to parse the JSON string.
Copied!
const obj = id: 1, name: 'bobby hadz', age: 30, salary: 1500, >; localStorage.setItem('my-object', JSON.stringify(obj)); const myObject = JSON.parse(localStorage.getItem('my-object')); // // "id": 1, // "name": "bobby hadz", // "age": 30, // "salary": 1500 // > console.log(myObject); console.log(myObject.name); // 👉️ 'bobby hadz'

retrieve object from localstorage

The JSON.parse() method parses the JSON string into a native JavaScript object.

Let’s look at an example of how you can render the retrieved from localStorage object.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> h2>bobbyhadz.comh2> ul id="unordered-list">ul> script src="index.js"> script> body> html>

Here is the code for the index.js file.

Copied!
const obj = id: 1, name: 'bobby hadz', age: 30, salary: 1500, >; localStorage.setItem('my-object', JSON.stringify(obj)); const myObject = JSON.parse(localStorage.getItem('my-object')); console.log(myObject); console.log(myObject.name); const ul = document.getElementById('unordered-list'); Object.entries(myObject).forEach(([key, value]) => const li = document.createElement('li'); li.innerHTML = `$key> - $value>`; ul.appendChild(li); >);

render object retrieved from localstorage

# How to store an Array of Objects in localStorage using JavaScript

The same approach can be used to store an array of objects in localStorage .

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> style> body margin: 100px; > style> head> body> h2>bobbyhadz.comh2> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const arrayOfObjects = [ id: 1, name: 'Alice'>, id: 2, name: 'Bobby Hadz'>, id: 3, name: 'Carl'>, ]; localStorage.setItem( 'arr-of-objects', JSON.stringify(arrayOfObjects), );

You can open your terminal in the same directory as the index.html and index.js files and issue the following command to start a development server.

array of objects stored in local storage

As shown in the screenshot, the array of objects is successfully stored in localStorage as a JSON string.

You can use the localStorage.getItem() method in combination with JSON.parse() to retrieve the array of objects from localStorage .

Copied!
const arrayOfObjects = [ id: 1, name: 'Alice'>, id: 2, name: 'Bobby Hadz'>, id: 3, name: 'Carl'>, ]; localStorage.setItem( 'arr-of-objects', JSON.stringify(arrayOfObjects), ); const myArrayOfObjects = JSON.parse( localStorage.getItem('arr-of-objects'), ); console.log(myArrayOfObjects); console.log(myArrayOfObjects[1]);

retrieve array of objects from local storage

Once we retrieve the JSON string using localStorage.getItem() , we pass the string to JSON.parse() to parse it into a native JavaScript array of objects.

Here is an example of how you can render the array of objects in the DOM.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> h2>bobbyhadz.comh2> ul id="unordered-list">ul> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const arrayOfObjects = [ id: 1, name: 'Alice'>, id: 2, name: 'Bobby Hadz'>, id: 3, name: 'Carl'>, ]; localStorage.setItem( 'arr-of-objects', JSON.stringify(arrayOfObjects), ); const myArrayOfObjects = JSON.parse( localStorage.getItem('arr-of-objects'), ); console.log(myArrayOfObjects); console.log(myArrayOfObjects[1]); const ul = document.getElementById('unordered-list'); arrayOfObjects.forEach(obj => const li = document.createElement('li'); li.innerHTML = `id: $obj.id> | name: $obj.name>`; ul.appendChild(li); >);

rendered array of objects in dom

We used the Array.forEach method to iterate over the array of objects.

On each iteration, we create a li item and set its innerHTML markup to a string that contains the id and name properties.

The last step is to append the li elements to the unordered list.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Javascript object to localstorage

Программирование на C++ в Unreal Engine 5

Программирование на C++ в Unreal Engine 5

Данный курс научит Вас созданию игр на C++ в Unreal Engine 5. Курс состоит из 12 разделов, в которых Вас ждёт теория и практика. Причём, в качестве практики будет создан весьма крупный проект объёмом свыше 5000 строк качественного кода, который уже на практике познакомит Вас с принципами создания игр на C++ в Unreal Engine 5.

Параллельно с курсом Вы также будете получать домашние задания, результатом которых станет, в том числе, полноценная серьёзная работа для портфолио.

Помимо самого курса Вас ждёт ещё и очень ценный Бонус: «Тестирование Unreal-проектов на Python», в рамках которого Вы научитесь писать очень полезные тесты для тестирования самых разных аспектов разработки игр.

Подпишитесь на мой канал на YouTube, где я регулярно публикую новые видео.

YouTube

Подписаться

Подписавшись по E-mail, Вы будете получать уведомления о новых статьях.

Подписка

Подписаться

Добавляйтесь ко мне в друзья ВКонтакте! Отзывы о сайте и обо мне оставляйте в моей группе.

Мой аккаунт

Мой аккаунт Моя группа

Какая тема Вас интересует больше?

Основы Unreal Engine 5

— Вы получите необходимую базу по Unreal Engine 5

— Вы познакомитесь с множеством инструментов в движке

— Вы научитесь создавать несложные игры

Общая продолжительность курса 4 часа, плюс множество упражнений и поддержка!

Чтобы получить Видеокурс,
заполните форму

Как создать профессиональный Интернет-магазин

Как создать профессиональный Интернет-магазин

— Вы будете знать, как создать Интернет-магазин.

— Вы получите бесплатный подарок с подробным описанием каждого шага.

— Вы сможете уже приступить к созданию Интернет-магазина.

Источник

Оцените статью