Javascript Array for JSON Array

I am using JSON to send Ajax data. I get a comma mobile number from the input text box. And I convert it to a 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 for my model as below:

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

Then the value becomes as follows:

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

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

So my model became this.model.toJSON();

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

So far, everything is correct. after that I need to install this model on another model, and running stringfy will give me the following:

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

"data": {"MobileNo": "[\" 123 \ "\" 456 \ "]"}

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

Your help will be appreciated.

+6
source share
1 answer

JSON.stringify creates a string from your array. This is clearly not what you want. Or is this what you want in this.model as you said

So far, everything is correct.

but in another model you want to set the array not as a string, but as an array. Since I don't know what you are doing with your backbone.js, I am writing it as pure javascript

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

must do the job. But you can just install

 data = { "mobileno": myarray } 

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

+7
source

All Articles