I need the following object:
var myObj={
"rules": {
"email": {
"required": true,
"email": true,
"remote": {
"url": "check-email.php",
"type": "post",
"data": {
"someName1": function() {
return $( '#someID1' ).val();
},
"someName2": function() {
return $( '#someID2' ).val();
},
"someName3": "bla"
}
}
}
}
};
To create it, I only have some JSON such as the following:
{
"rules": {
"email": {
"required": true,
"email": true,
"remote": {
"url": "check-email.php",
"type": "post",
"data": {
"someName1": {"id":"someID1"},
"someName2": {"id":"someID2"},
"someName3": "bla"
}
}
}
}
}
or
{
"rules": {
"email": {
"required": true,
"email": true,
"remote": {
"url": "check-email.php",
"type": "post",
"data": {
"someName1": {"function":"return $( '#someID1' ).val()"},
"someName2": {"function":"return $( '#someID2' ).val()"},
"someName3": "bla"
}
}
}
}
}
or something similar.
How can this be accomplished?
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] = new Function(d[key].function);
//Note: You might want to check if d[key].function exists before using it.
});
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();
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With