Print array in JSON

0

I need an array that I put into a JSON and store it in localStorage can add a value to an array that is already saved

Here is where I keep the arrangement:

var palabra = $("#txtpalabra").val();

        var pista =  $("#txtpista").val();

        Palabras.push(palabra);
        Pistas.push(pista);
        localStorage.setItem("Palabras", JSON.stringify(Palabras));
        localStorage.setItem("Pistas", JSON.stringify(Pistas));

And he keeps it like this:

0:"santos" 1:"laguna"

And I need you to keep it that way:

0:{"santos", "laguna"}
    
asked by Carlos Roberto Luna Ochoa 06.06.2018 в 19:18
source

2 answers

0

JSON has the structure of {key: value, key: value} Maybe what you want is this:

{
    palabras: ["palabra1", "palabra2"],
    pistas: ["pista1", "pista2"]
}
    
answered by 06.06.2018 в 19:31
0

You must parse what you get from the LocalStorage since you get a string and you need it to be an array again, here is a functional example of how to save two arrays in the LocalStorage and get them again:

var Palabras = ['hola', 'javascript']
var Pistas = ['j', 's']

// Guardas en LocalStorage los valores en forma de cadena usando JSON.stringify

localStorage.setItem('Palabras', JSON.stringify(Palabras))
localStorage.setItem('Pistas', JSON.stringify(Pistas))

// Obtienes los valores y los parseas con JSON.parse

Palabras = JSON.parse(localStorage.getItem('Palabras'))
Pistas = JSON.parse(localStorage.getItem('Pistas'))

// Estos son arrays
console.log(Palabras[1]) // 'javascript'
console.log(Pistas[0]) // 'j'
    
answered by 07.06.2018 в 07:13