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?
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?
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));
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'))
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'));
You may try like this:
var multidimensionarray = [
['1','2'],
['3','4']
];
localStorage.setItem('__array', JSON.stringify(multidimensionarray));
console.log(localStorage.getItem('__array'));
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(...)