Confusions with JSON.stringify, JSON.parse and OBJECT.push()

Asked

Viewed 833 times

2

Well I’m cluttering up with these commands, in fact what I’m wanting to do is the following. Using localStorage maintain a database.

NOME TABELA | DADOS TABELA
tbl_TESTE   | {teste 01, teste02, teste03, ...}
tbl_TESTE02 | {arroz, feijão, batata, ...}

**Sendo que todos os dados da tabela é um array de OBJETOS.

When I start the application I set the banks as null I do so:

localStorage.setItem("tbl_TABELA01", []);
localStorage.setItem("tbl_TABELA02", []);
localStorage.setItem("tbl_TAVELA03", []);

This is done only once to not reset the data already entered.

After inserting I do as follows:

var nome = $("#lblNome").val(),
    telefone = $("#lblTelefone").val();

var dados = [];

   dados.lbNome = nome;
   dados.lbTelefone = telefone;

   console.log(dados);

//var result = JSON.stringify(dados);

// console.log(result);

var tbl_CELULAS = localStorage.getItem("tbl_CELULAS");

   console.log(tbl_CELULAS);

// var parsetbl_CELULAS = JSON.parse(tbl_CELULAS);

// console.log(parsetbl_CELULAS);

     tbl_CELULAS.push(dados);

console.log(tbl_CELULAS);

//var JSON = JSON.stringify(tbl_CELULAS);

  console.log(JSON);

This is a mess because I do not know how to assemble logic to solve the problem. What I need is before I insert, to search for what I already have in localStorage, thus inserting in last position what I just looked for, then last save again in localStorage.

  • if you need to maintain a structure similar to a table, it is not better to use the IndexedDB?

  • @Tobymosque I use, however the indexedDB is giving me problem with portability in old Androids, and the solution to not have more headache is this

  • knows the Storage.js, it promises a unique interface to DOM Storage, WebSQL and IndexedDB. you can tell us what technology you will use, if you don’t, it will try to use the IndexedDB, then the WebSQL, finally the localStorage.

  • @Tobymosque But how would you use tables ?

  • storage(function (context) { context.set("nome entidade", { id: 2, desc: "desc" }, function () { context.get("nome entidade", 1, function(value) { console.log (value.desc) })})})

1 answer

4


localStorage stores strings. When you want to reset you must pass strings to Setter, that is to say at the same time localStorage.setItem("tbl_TABELA01", []); you must have localStorage.setItem("tbl_TABELA01", '[]');

If you want to be sure of the recording order you have to use arrays. Using Objects, and Object.keys(), does not return keys in order of insertion.

When you do var tbl_CELULAS = localStorage.getItem("tbl_CELULAS"); this returns a string and not a pointer that you can change by reference. In localStorage you have to read everything (in string) and write everything again (in string) to record changes.

Those aspects I mentioned are important. So what you want to do is something like this:

// fazer o reset
["tbl_TABELA01", "tbl_TABELA02", "tbl_TABELA03"].forEach(function(str) {
    localStorage.setItem(str, '[]');
});


var nome = $("#lblNome").val();
var telefone = $("#lblTelefone").val();

var tbl_CELULAS = localStorage.getItem("tbl_CELULAS"); // buscar a string que está gravada
var dados = JSON.parse(tbl_CELULAS); // para ler e mudar como uma array
var novosDados = { // criar um novo objeto
    lbNome: nome,
    lbTelefone: telefone
};
dados.push(novosDados); // inserir na variável/array
var json = JSON.stringify(dados); // para voltar a ter tudo em string com os novos dados
localStorage.setItem("tbl_CELULAS", json); // escrever a string no localStorage

Note:

don’t use var JSON = JSON.stringify(tbl_CELULAS);! you will be deleting the native method. How much with small letter, to be another variable.

  • 1

    had a small error in the initialization of the objects, no longer remained the answer was perfect.

  • @Tobymosque thank you!

  • Take me just one more question, I also have a JSON coming from AJAX, how would you save it ? As automated as possible ?

  • 1

    @Renanrodrigues if this JSON is in string writes directly, otherwise you have to do var string = JSON.stringify(dadosDoAjax);. You can check by doing alert(typeof dadosDoAjax); to know that Type is returned by ajax.

Browser other questions tagged

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