Requirement:
A JSON object that may contain null values or an empty string that you want to encounter when the page is displayed with a null value showing "n/a", but there is a partial value that allows null values. For this reason, you want to set the null value to "N/a" by filtering. For example, you want the student's "Age" and "score" to display "N/a" blank, and "sex" or "comment" blank.
Copy Code code as follows:
var student = {
"Name": "Guo",
"Sex": "",
"Age": "",
"num": 01,
"Scores": [
{
"Subject": "中文版",
"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 Results
Method 2 Results