noobcode0000
noobcode0000

Reputation: 243

How would I push an input value into an array for localstorage?

I have a block of code that saves the input into localStorage, however, when I look into localStorage it is not formatted properly. This is the code:

var selectN = document.getElementById("select").value;
var arr= JSON.parse(localStorage.getItem("Table"));
var arr2 = [arr]
arr2.push(selectN);
localStorage.setItem("Table", JSON.stringify(arr2));

However it ends up formatting like this: [["", "Data1"], "Data2"] which is not what I am looking for. I am looking for something like this ["", "Data1", "Data2"] However it seems that I am getting the same result. I have even tried:

const arr = [JSON.parse(localStorage.getItem('Data'))];
    const arr2 = [
      ...arr,
      selectN
    ]

Any help would be appreciated.

Upvotes: 0

Views: 616

Answers (2)

Obaida Alhassan
Obaida Alhassan

Reputation: 601

You need to parse the table values to an array "if there is value since the first time the Table will be null", and then add the selected values to the table arr then stringify the arr and set it in the local storage, Here is the snippet of code

var selectN = ["Data1", "Data2"]
var table = localStorage.getItem("Table");
var arr = []

if(table)
 arr = JSON.parse(table);

 arr.push(...selectN);


localStorage.setItem("Table", JSON.stringify(arr));

console.log(localStorage.getItem("Table"))
// ["Data1","Data2"]

Upvotes: 2

Maik Lowrey
Maik Lowrey

Reputation: 17566

I saw that you put the array inside an new array. that is the reason why you got this new array structur.

  1. Get the value from localStorage.
  2. parse the string to an array
  3. push to this array the value from your select.
  4. stringify the array
  5. save it to the localstorage again
var arr = JSON.parse(localStorage.getItem("Table"));
// arr output ["Data1"]
data.push( document.getElementById("select").value );
localStorage.setItem("Table", JSON.stringify(arr2));

Upvotes: 0

Related Questions