I have this Json data I get from server in javascript
var mydata = JSON.parse('["X","Y","Z"]');
Below I have the following data model in javascript..
var mySchemasList = {
schemas: [new SelectSchemaModel("A", false),
new SelectSchemaModel("B", false),
new SelectSchemaModel("C", false)
]
};
I want to create this model dynamically by getting data ('A','B','C') from mydata..
Any help is sincerely appreciated..
Thanks
Can't you just do something like the following?
var i
var mySchemaList = {schemas:[]};
for (i = 0; i < mydata.length; i++) {
mySchemaList.schemas.push( new SelectSchemaModel(mydata[i], false) );
}
In javascript, objects and arrays are accessed using the .
or []
operators. The following two lines does exactly the same thing:
mySchemasList.schemas;
mySchemasList['schemas'];
Also, each member of an object or array act like a variable on its own. So you can assign values, objects or arrays to them:
mySchemasList = {};
When a variable (or property) is declared but not assigned anything its value is undefined
. So you can check simply by:
if (mySchemasList === undefined) mySchemasList = {};
Alternatively you can use ||
short circuiting since undefined
is considered false:
mySchemasList = mySchemasList || {};
putting this all together, the following two examples does exactly the same thing.
Example 1:
var mySchemasList = {
schemas : []
}
Example 2:
var mySchemasList = {};
mySchemasList.schemas = [];
Now that you've created an array at mySchemasList.schemas
you can start pushing other objects into it:
mySchemasList.schemas.push(new SelectSchemaModel("A", false));
mySchemasList.schemas.push(new SelectSchemaModel("B", false));
mySchemasList.schemas.push(new SelectSchemaModel("C", false));
Wrapping it up in a for loop parsing the JSON data, you'd do this:
var mydata = JSON.parse(ajax.responseText);
for (var i=0; i<mydata.length; i++) {
mySchemasList.schemas.push(new SelectSchemaModel(mydata[i],false));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.