In this article, I will introduce you to some small series. In jQuery, you can refer to any of you who need to filter and replace json empty objects.
Requirement:
A json object may contain null values or empty strings. When displayed on the page, you want to display "N/A" for A null value, but some values allow null values. Therefore, you want to set the null value to "N/A" by filtering ". for example, if the student's "age" and "score" are empty, "N/A" is displayed, and "sex" or "comment" is empty, no processing is required.
The Code is as follows:
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/";
}
}
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/";
}
}
}
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/";
}
});
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/";
}
});
}
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 Result
Method 2 result