1

store data and retrieve multidimensional array in local storage java-script

Here I need to store array in local storage. and How do I retrieve?

dhina2525
  • 147
  • 2
  • 8
  • 1
    Please try to at least search for answers before asking a question: https://www.google.com/search?q=store+array+in+localstorage&oq=sotre+array+in+loca&aqs=chrome.1.69i57j0l5.3632j0j7&sourceid=chrome&ie=UTF-8 – Kobe Jul 09 '19 at 09:51

5 Answers5

4

As only strings can be assigned to localStorage, you have to convert the array to a string before assigning. Convert the array into a JSON string using JSON.stringify() and using localStorage.setItem() store it in localStorage.

var num = [
    ['inp1','inp2'],
    ['inp3','inp4']
];
localStorage.setItem('arr',JSON.stringify(num));
ellipsis
  • 12,049
  • 2
  • 17
  • 33
1

You can use JSON.stringify() and JSON.parse() combined with Window.localStorage methods setItem() and getItem():

To store:

localStorage.setItem('myItem', JSON.stringify(myMultidimensionalArray))

And to get the stored data with key myItem:

const array = JSON.parse(localStorage.getItem('myItem'))
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
1

With localStorage we are limited to store data as strings, therefore:

  • Use JSON.stringify to serialize the data to a string, before storing it in the local storage

    const input = [[1], [2], [3]];
    localStorage.setItem('myData', JSON.stringify(input));
    
  • Use JSON.parse to deserialize the data back to array when reading it form the local storage

    const arr = JSON.parse(localStorage.getItem('myData'));
    
antonku
  • 7,377
  • 2
  • 15
  • 21
1

You may try like this:

var multidimensionarray = [
   ['1','2'],
   ['3','4']
];
localStorage.setItem('__array', JSON.stringify(multidimensionarray));

console.log(localStorage.getItem('__array'));
Shivani Sonagara
  • 1,299
  • 9
  • 21
0

Local storage is very simple data storage. It stores key (string) of which value is also (string and only string!). You need to use JSON.stringify(...) to store data and then parse it back JSON.parse(...)

jank
  • 840
  • 4
  • 7