您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

在jQuery中 关于json空对象筛选替换_jquery

2024/3/15 8:34:15发布38次查看
requirement:一个json object,并且可能包含一些空值或者空字符串,在页面显示的时候希望遇到空值显示“n/a”,但是有一部分值是允许空值的。因此希望通过筛选将空值设为“n/a”.例如希望学生的“age”和“score”如果为空显示“n/a”,而“sex”或者“comment”为空则不做处理。
复制代码 代码如下:
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 结果
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product