Requirement:
A json object, and may contain some null values or empty strings. When displaying the page, it is expected to display "N/A" when encountering null values, but some values allow null values. Therefore, we hope to set the null value to "N/A" through filtering. For example, we hope that if the student's "age" and "score" are empty, "N/A" will be displayed, and "sex" or "comment" will not be processed if they are empty. .
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 < 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 < 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 结果