1

I am trying to store array in localstorage with following code :

var tempval = [];
tempval['key'] = 1;                    
localStorage.setItem("Message", JSON.stringify(tempval));

but in localstorage it showing only []

So how to store it and where I am doing mistake ?

Cloud
  • 1,004
  • 1
  • 18
  • 47
Er.KT
  • 2,852
  • 1
  • 36
  • 70
  • 1
    This is wrong in so many ways. But let me ask you of the first obvious `Where's the multidimensional array?` This `[ [1,2] , [3,4]]` is multidimensional array, array in array – kidwon Jun 20 '16 at 10:38
  • The array you created is just like associative array and its complicated in javascript. Because js doesn't support associative array. – Cloud Jun 20 '16 at 10:39
  • I understand that you want to insert `object` you try to do this `tempval.push({'key':1})`. but `multidimensional array` ? – elreeda Jun 20 '16 at 10:40
  • What you do in my opinion is you set a property of the array treating it as object but it is still empty array. So the string representation of empty array is empty array. – kidwon Jun 20 '16 at 10:42
  • This question has been answer already (duplicate of): https://stackoverflow.com/a/3357615/10387837 – Alvaro Lamadrid Jul 04 '19 at 23:29
  • Possible duplicate of [How do I store an array in localStorage?](https://stackoverflow.com/questions/3357553/how-do-i-store-an-array-in-localstorage) – Alvaro Lamadrid Jul 05 '19 at 23:57

4 Answers4

0

Here is your code:-

var tempval ={};
tempval.key = 1;                    
localStorage.setItem("Message", JSON.stringify(tempval));
Gaurav Srivastava
  • 3,232
  • 3
  • 16
  • 36
0

JavaScript does not support arrays with named indexes.Arrays always use numbered indexes in javascript. Use object if you wanna use named index.

Using array (numbered index)

var tempval = [];
tempval[0] = 1;

Using object (named index)

 var tempval = {};
 tempval['key'] = 1;

Use var tempval ={}; instead of var tempval = [];

zakhefron
  • 1,403
  • 1
  • 9
  • 13
0

So Your Question is not that much clear to me but i am trying to give you a general solution for storing multidimensional array in local storage ,

    var a= [[1,2,3],["hello","world"]]; // multi dimentional array 
    console.log(a);
    var b = JSON.stringify(a); // converting the array into a string 
    console.log(b);
    localStorage.setItem("TestData",b); // storing the string in localstorage
    var c= JSON.parse(localStorage.getItem("TestData")); //accessing the data from localstorgae.
    console.log(c);

Here is the code running in Jsbin

Partha Roy
  • 1,575
  • 15
  • 16
0

This question has been answer already (duplicate of):

https://stackoverflow.com/a/3357615/10387837

The short answer is localStorage.setItem only supports strings as arguments. In order to use it with arrays its recommended to use JSON.stringify() to pass the parameter and JSON.parse() to get the array.

Alvaro Lamadrid
  • 355
  • 2
  • 13