Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
Views
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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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"]
about 4 years ago · Juan Pablo Isaza Report

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));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!