0

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.

3
  • Cause you are wrapping the value arr in another array arr2, var arr2 = [arr] this will add the value inside another dimension array Commented Oct 15, 2021 at 12:05
  • var arr2 = [arr] => you put the array into an new array. is that how it should be? Commented Oct 15, 2021 at 12:06
  • I have added an answer with a snippet of code Commented Oct 15, 2021 at 12:17

2 Answers 2

2

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"]
Sign up to request clarification or add additional context in comments.

Comments

0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.