Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array to JSON array

I am using JSON to send Ajax data. I am getting comma separated mobile number from the input text box.And, I am converting it into javascript array.
Below is my code:

  var myarray = {};
    myarray = this.model.get('mobileno').split(',');

Result : myarray : ["123", "4567"];

I am going to set the same value to my model like below:

this.model.set('mobileno',JSON.stringify(myarray ));

Then, the value becomes like below:

console.log(this.model.get('mobileno'));

Result : mobileno : "["123","4567"]"

So, my model become this.model.toJSON();

Result :Object {mobileno: "["123","4567"]}

Till here, everything is correct. after that I need to set this model to another model and doing stringfy will give me like Below:

 anotherModel.set('data', this.model);

"data":{"mobileno":"[\"123\",\"456\"]"}

But, I need like "data":{"mobileno":["123","456"]}

Your help will be appreciated.

like image 857
Madhukar Hebbar Avatar asked Jul 05 '15 09:07

Madhukar Hebbar


Video Answer


1 Answers

JSON.stringify makes a string from your array. That is obviously not what you want. Or it is what you want in this.model as you said

Till here everything is correct.

but in the other model, you want to set the array not as a string, but as the array. As I don't know what you are doing with your backbone.js I write it as pure javascript

data = JSON.parse(this.model.get("mobileno"))

should do the job. But you can just set

data = { "mobileno": myarray }

BTW. if the backbone.js does nothing more than confusing the javascript object and array notation, I would recommend not to use it at all. As you told us the backbone.js this.model.get('mobileno') returns an object containing the mobileno field. In my world of logic anything.get('XY') should return the value of XY not an object containing the XY property.

like image 200
ikrabbe Avatar answered Oct 13 '22 07:10

ikrabbe