Hi, I have a problem with the next code:
javascript
var cadena="[";
$('.box').each(function(){
var clase=$(this).attr("class");
var id_t=$(this).attr("id");
if(clase=="box todo"){
var status_t="todo";
//alert('hola');
}
if(clase=="box inprocess"){
var status_t="inprocess";
//alert('hola');
}
if(clase=="box testing"){
var status_t="testing";
//alert('hola');
}
if(clase=="box done"){
var status_t="done";
//alert('hola');
}
//alert('tarea es: '+id_t+ ' con clase '+status_t);
var objeto={};
objeto["id"]=id_t;
objeto["status"]=status_t;
var json = JSON.stringify(objeto);
//alert(json);
cadena=cadena+json;
});
cadena= cadena+"]";
alert('cadena Json '+cadena);
I get this chain Json, but this chain is wrong because it need be separate with (,) I haven't idea that do
[
{"id":"1","status":"1"}
{"id":"2","status":"2"}
{"id":"3","status":"1"}
]
and I need a chain Json valid, I want something similar to this
[
{"id":"1","status":"1"},
{"id":"2","status":"2"},
{"id":"3","status":"1"}
]
any ideas to take me to this result I will be very grateful. THANKS!!!
2 Answers 2
You're doing it wrong. Instead of the below line,
var cadena = "["
try
//to init array
var cadena = [];
And, instead of this line,
cadena = cadena+json;
Try this
cadena.push(json);
And remove this line :
cadena= cadena + "]";
For more info, see this question : How to append something to an array?.
And you could simplify your code to this :
$('.box').each(function () {
//taking out the second element of the class and assigning it directly to status_t variable
var status_t = $(this).attr("class").split(" ")[1];
var id_t = $(this).attr("id");
var objeto = { "id" : id_t, "status" : status_t};
cadena.push(json);
});
Comments
I think I would do it like this:
var cadena = $('.box').map( function( e ) {
var $e = $(e);
return {
id: $e.attr('id'),
status: $e.attr('class').replace( /^box /, '' )
}
});
var json = JSON.stringify( cadena );
console.log( json );
I don't have a way to test that, but unless I missed something it should work. If you post some sample HTML I could make sure it's correct.