复制代码 代码如下:
var student = {
name : guo,
sex : ,
age : ,
num : 01,
scores : [
{
subject : english,
score : 50,
comment :
},
{
subject : computer,
score : ,
comment : absent
}
]
};
var exclude = [sex, comment];
// method 1 to validate obj
validateobj1 = function(obj, excluded){
var value;
for(var key in obj){
value = obj[key];
if($.isarray(value)){
obj = validatearray1(obj, key, excluded);
}else if(($.inarray(key, excluded) == -1) && ($.isblank(value))){
obj[key] = n/a;
}
}
return obj;
}
validatearray1 = function(obj, key, excluded){
var subvalue;
for(var i = 0, length = obj[key].length; i for(var subkey in obj[key][i]){
subvalue = obj[key][i][subkey];
if(($.inarray(subkey, excluded) == -1) && ($.isblank(subvalue))){
obj[key][i][subkey] = n/a;
}
}
}
return obj;
}
// method 2 to validate obj
validateobj2 = function(obj, excluded){
$.each(obj ,function(key, value){
if($.isarray(value)){
obj = validatearray2(obj, key, excluded);
}else if(isinvalid(key, value, excluded)){
obj[key] = n/a;
}
});
return obj;
}
validatearray2 = function(obj, key, excluded){
for(var i = 0, length = obj[key].length; i $.each(obj[key][i] ,function(subkey, subvalue){
if(isinvalid(subkey, subvalue, excluded)){
obj[key][i][subkey] = n/a;
}
});
}
return obj;
}
isinvalid = function(key, value, excluded){
return (($.inarray(key, excluded) == -1) && ($.isblank(value))) ? true : false;
}
$.isblank = function(obj){
return(!obj || $.trim(obj) === );
};
method 1 结果
method 2 结果
