Remove garbage from an array

0

I have the following code: what I try to do is that when a new user wants to register in my project he must fill out the form 3 times once sent 3 times the record will be successful . For this reason I use localStorage to save the data of the first, second and third sending of the form.

The code that I present in reality is an abstraction (minimum, complete and verifiable) of my real code (it would be a lot of code).

The code I publish does not work on SOes (I do not know why), please try it locally.

    var nombreAux = "";
var apellidoAux = "";
var dato_G = []; //tiempo de presion y realce
var dato_aux = [];

var iteracion = 0;

$(window).on('load', function () {
$('#add-new-fact').click(function () {
	var nombreUser = $('#nom').val();
	var passUser = $('#pass').val();
	var dato = $('#dato').val();
	dato_aux.push(dato);

	if (nombreUser != "" && passUser != "") {

		/*Guardando los datos en el LocalStorage*/
		nombreAux = localStorage.getItem("Nombre");
		apellidoAux = localStorage.getItem("contrasena");
		// alert(nombreAux+" "+apellidoAux);
		if ((nombreAux == "" || apellidoAux == "")) {
			localStorage.setItem("Nombre", nombreUser);
			localStorage.setItem("contrasena", passUser);
		}
		nombreAux = localStorage.getItem("Nombre");
		apellidoAux = localStorage.getItem("contrasena");

		if (((nombreUser != nombreAux || passUser != apellidoAux))) { //cuando es nuevo user
			localStorage.setItem("Nombre", nombreUser);
			localStorage.setItem("contrasena", passUser);
			dato_G.push(JSON.stringify(dato_aux));
			localStorage['dato'] = dato_G;
			dato = [];
		}

		if ((nombreUser == nombreAux || passUser == apellidoAux) && (iteracion < 6) && (typeof dato != undefined)) { //cuando ya es un usuario
			iteracion++;
			if (dato.length > 0) {
				dato_G.push(JSON.stringify(localStorage['dato']));
				dato_G.push(JSON.stringify(dato_aux));
				dato_aux = [];
			}

			localStorage['dato'] = dato_G;
		}

		alert(localStorage['dato']);

		location.reload();

		if (iteracion == 3) {

			//por medio de ajax recien envio los datos para su registro en la BD

		}
		return false;

	}
	alert(localStorage['dato']);
	nombreUser = "";
	passUser = "";
});
});
<!DOCTYPE html>
<html>
<head>
	<title></title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="main.js"></script>
</head>
<body>

<input id="nom" type="text" placeholder="nombre">
<input id="pass" type="text" placeholder="pass">
<input id="dato" type="text" placeholder="dato">
<a href="#" id="add-new-fact" >enviar</a>

</body>
</html>

The result generates a array "infected" or with garbage, similar to the screenshot below:

I would like to stay with only the arrays . Is it possible?

Note: As you are inserting array it will fill with more garbage.

How to avoid that garbage? Why is it generated?

    
asked by hubman 30.12.2016 в 08:01
source

2 answers

2

Honestly, I get a little dizzy trying to interpret the code, so I'm going to post a partial response, hoping it will work for you.

The problem is that you are using JSON.stringify() on a variable that is already a JSON, so it ends up escaping the characters more than once.

To solve this, when manipulating the value of dato , do not try to convert it from / to JSON into the main part of your code, handle it as an object without converting it. And, then, the conversion would be done only when saving or reading from localStorage.

function recuperarDato(clave) {
    return JSON.parse(localStorage.getItem(clave));
}

function guardarDato(clave, objeto) {
    localStorage.setItem(clave, JSON.stringify(objeto));
}

So, to save:

guardarDato("dato", dato_G);

And to read it:

dato_G = recuperarDato("dato");
    
answered by 30.12.2016 в 22:32
1

To solve my problem I had to use JSON.stringify and JSON.parse , and not only JSON.stringify() as I posted in the question.

 var nombreAux   = "";
    var apellidoAux ="";
    var dato_G= []; //tiempo de presion y realce
    var dato_aux=[];

var iteracion=0;


$(window).on('load', function() {  
    $('#add-new-fact').click(function() {
    var nombreUser = $('#nom').val();
    var passUser = $('#pass').val();
    var dato = $('#dato').val();
    dato_aux.push(dato);

if(nombreUser!="" && passUser!=""){

/*Guardando los datos en el LocalStorage*/
    nombreAux   = localStorage.getItem("Nombre");
    apellidoAux = localStorage.getItem("contrasena");
// alert(nombreAux+" "+apellidoAux);
   if((nombreAux==""||apellidoAux=="")){
        localStorage.setItem("Nombre", nombreUser);
        localStorage.setItem("contrasena", passUser);
    }
    nombreAux   = localStorage.getItem("Nombre");
    apellidoAux = localStorage.getItem("contrasena");

    if(((nombreUser!=nombreAux || passUser!=apellidoAux))){//cuando es nuevo user
        localStorage.setItem("Nombre", nombreUser);
        localStorage.setItem("contrasena", passUser);
        dato_G.push(JSON.stringify(dato_aux));
        localStorage['dato']=JSON.stringify(JSON.parse(dato_G));
        dato=[];
    }

    if((nombreUser==nombreAux || passUser==apellidoAux) && (iteracion<3) &&(typeof dato!=undefined) ){//cuando ya es un usuario 
        iteracion++;
        if(dato.length>0){
            dato_G.push(localStorage['dato']);
            dato_G.push(JSON.stringify(dato_aux));
            dato_aux=[];    
        }

        localStorage['dato']=dato_G; 
  }

    alert(localStorage['dato']);

location.reload();

if(iteracion==3){
alert("enviando");
    //por medio de ajax recien envio los datos para su registro en la BD

}
    return false;

}
alert(localStorage['dato']);
    nombreUser="";
    passUser="";
  });

});
    
answered by 30.12.2016 в 22:39