Map a JSON object to a Javascript class -


i want know "good practice" map json object javascript instance class.

my example have database of cards in json file. each card has several attributes. have class card has same attributes plus several methods. how map cards in json file instances of class card, without copying each attribute 1 one if able ?

i have json objects json file. here example have 700 objects these :

{"cycleid":1,"setid":1,"cardid":27,"nameen":"ninja","namefr":"ninja","side":"runner","cardtypes":["program","ice_breaker","killer"],"nbcopies":3,"rarity":"unco"}, {"cycleid":1,"setid":1,"cardid":29,"nameen":"bank job","namefr":"casse","side":"runner","cardtypes":["resource"],"nbcopies":3,"rarity":"common"} 

i retrieve these json file ajax request :

$.ajax({         url: databaseurl,         beforesend: function(xhr){           if (xhr.overridemimetype)           {             xhr.overridemimetype("application/json");           }         },         async:true,         global: false,         datatype: 'json',         data:fieldstring,         success: function(data, status, request) {           // >> here want map json data class instances <<         }       }); 

the class card map json data :

function card(cycleid, setid...) {   // 1 example of method   this.calculatescore = function(cardtypes, rarity) {     var score = 0;     // calculates score of card according specified parameters , attributes of card     ...     return score;   } } 

thank help.

not sure if you're asking this

function card(obj) {   // attributes of "obj" map class   var keys = ["cardtypes", "rarity", ...];   (var key in obj) {       if (obj.hasownproperty(key) && keys.indexof(key) !== -1) {           this[key] = obj[key];       }   }   // 1 example of method   this.calculatescore = function(cardtypes, rarity) {     var score = 0;     // calculates score of card according specified parameters , attributes of card     ...     return score;   } } 

Comments

Popular posts from this blog

How to connect android app to App engine -

gcc - MinGW's ld cannot perform PE operations on non PE output file -

php - display validation error message next to the textbox in codeigniter -