Skip to content Skip to sidebar Skip to footer

Creating Js Object With Methods From Json

I need the following object: var myObj={ 'rules': { 'email': { 'required': true, 'email': true, 'remote': { 'url': '

Solution 1:

You can use Function to create functions on the fly. Supposing you have the second JSON structure:

d = obj.rules.email.remote.data;
Object.keys(d).forEach(function(key) {
    d[key] = newFunction(d[key].function); 
    //Note: You might want to check if d[key].function exists before using it.
});

Solution 2:

For this pattern :

{"rules":{"email":{"required":true,"email":true,"remote":{"url":"check-email.php","type":"post","data":{"someName1":{"id":"someID1"},"someName2":{"id":"someID2"},"someName3":"bla"}}}}}

Can be done as:

for(var key in myObj.rules.email.remote.data){
    if(myObj.rules.email.remote.data[key].id){
    myObj.rules.email.remote.data[key] = function(){
          return $('#'+myObj.rules.email.remote.data[key].id).val();
        }
    }
}

if email is not hardcoded then it can be done as:

for(var key1 in myObj.rules){
 for(var key in myObj.rules[key1].remote.data){
        if(myObj.rules[key1].remote.data[key].id){
        myObj.rules[key1].remote.data[key] = function(){
              return $('#'+myObj.rules[key1].remote.data[key].id).val();
            }
        }
    }
}

Post a Comment for "Creating Js Object With Methods From Json"