store an array of objects in a local storage with JS

1

I'm a bit lazy with JavaScript and I'm trying to create an array of objects to save data from a form with localStorage , but I'm not sure how to do that.

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

I want to create an array to put 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");
}
    
asked by anonymous 13.09.2018 / 05:13

3 answers

2

You must use array to store the values. To save on localStorage , just use JSON.stringify .

In the capture it is necessary to parse ( parse ) the object returned, so 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>
    
13.09.2018 / 08:53
1

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

I've 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.');
}
    
13.09.2018 / 14:08
0

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

function savePassword () {

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

}

    
25.09.2018 / 03:11