Reputation: 243
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
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
Reputation: 17566
I saw that you put the array inside an new array. that is the reason why you got this new array structur.
var arr = JSON.parse(localStorage.getItem("Table"));
// arr output ["Data1"]
data.push( document.getElementById("select").value );
localStorage.setItem("Table", JSON.stringify(arr2));
Upvotes: 0