store an array of objects in a Storage location with JS

Asked

Viewed 10,794 times

4

I’m a little layy with Javascript and I’m trying to create a array of objects to save data from a form with the localStorage, but I don’t know how to do it.

I already created the code to store the data in the local storage, but saves only one object, whenever I reload the page and fill in the data again, the old data is overwritten.

I want to create a array to place all the objects I create.

Code:

function salvarPessoa(){
    var nome = document.getElementById("nome").value;
    var cpf = document.getElementById("cpf").value;

    var pessoa = {nome: nome, cpf: cpf};

    pessoa_json = JSON.stringify(pessoa);

    localStorage.setItem("pessoa", pessoa_json);

    alert("Salvo com Sucesso");
}

3 answers

4

It is necessary that you use a array to store values. To save to localStorage, just use the JSON.stringify.

In the capture it is necessary to analyze (parse) the returned object, for this we can use JSON.parse.

Commented example:

Javascript:

/**
 * Elementos
 */
const inputPeople = document.querySelector("input")
const btnSavePeople = document.querySelector("button")
const result = document.querySelector("#result ol")

/**
 * Função responsável por salvar os dados
 */
btnSavePeople.addEventListener("click", _ => {
  let peoples = new Array()

  /**
   * Verifica se a propriedade existe
   * Caso exista, converte de String para Object
   */
  if (localStorage.hasOwnProperty("peoples")) {
    peoples = JSON.parse(localStorage.getItem("peoples"))
  }

  /* Adiciona um novo valor no array criado */
  peoples.push({name: inputPeople.value})

  /* Salva o item */
  localStorage.setItem("peoples", JSON.stringify(peoples))

  /* Exibe o resultado */
  result.insertAdjacentHTML('beforeend', `<li>${inputPeople.value}</li>`)
})


/**
 * Função responsável por carregar o conteúdo
 */
window.addEventListener("load", _ => {
  if (localStorage.hasOwnProperty("peoples")) {
    JSON.parse(localStorage.getItem("peoples")).forEach(people => {
      result.insertAdjacentHTML('beforeend', `<li>${people.name}</li>`)
    })    
  }
})

HTML:

<input type="text" />
<button>Save People</button>

<div id="result"><ol></ol></div>

3

Your code is almost working, just get the people who are already saved with Storage.getItem(), add the new person to the array (Array.push()) and save back (Storage.setItem()).

I changed your code:

function salvarPessoa(){
    var nome = document.getElementById("nome").value;
    var cpf = document.getElementById("cpf").value;

    // Pega a lista já cadastrada, se não houver vira um array vazio
    var lista_pessoas = JSON.parse(localStorage.getItem('lista-pessoas') || '[]');
    // Adiciona pessoa ao cadastro
    lista_pessoas.push({
        nome: nome,
        cpf: cpf
    });

    // Salva a lista alterada
    localStorage.setItem("lista-pessoas", JSON.stringify(lista_pessoas));

    console.log('Salva com sucesso.');
}

1

Guys like this, I can solve but now I wonder how to access this json to access the information and create a login function; my save function was like this...

Function salvarPessoa(){

var arrayPessoas=[]
if(JSON.parse(localStorage.getItem("pessoas")) != null){
    arrayPessoas.push(JSON.parse(localStorage.getItem("pessoas")));
}
var nome = document.getElementById("inputNome").value;
var cpf = document.getElementById("inputCPF").value;
var idade = document.getElementById("inputIdade").value;
var telefone = document.getElementById("inputTelefone").value;
var email = document.getElementById("inputEmail").value;
var senha = document.getElementById("inputSenha").value;

var pessoa = {nome: nome, cpf: cpf, idade: idade, telefone: telefone, email: email, senha: senha};
console.log(pessoa);
arrayPessoas.push(pessoa);
var pessoaJson = JSON.stringify(arrayPessoas);
localStorage.setItem("pessoas", pessoaJson);

alert("Salvo com Sucesso");

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.