Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

198
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda