页首 HTML 代码 ----

js中一个移除对象中子数组中空值的函数

js中一个移除对象中子集数组中空值(null,undefined)的函数

function removeNull(obj){
    let delarr = [];
    for(let i in obj){
        // 排除法寻找对象类型
        if(typeof(obj[i]) === 'boolean' ||
        typeof(obj[i]) === 'string' ||
        typeof(obj[i]) === 'number' ||
        typeof(obj[i]) === 'bigint' ||
        typeof(obj[i]) === 'symbol' ||
        typeof(obj[i]) === 'function' 
        // 如果你有其他类型的在这里声明一下
        ) continue;
        if(obj[i] == null || obj[i] == undefined){
            delarr.push(i);
        }else{
            this.removeNull(obj[i]);
        }
    }
    while(delarr.length>0){
        if(obj.length != undefined){
            // 数组
            obj.splice(delarr.pop(),1);
        }else{
            // 对象
            // 暂时还没找到处理方法
            delarr.pop();
        }
    }
    return obj;
}

测试函数:

let a = {b:null,c:[null,1,2,null,null],d:{aa:1,bb:2,cc:null,dd:undefined}}
console.log(JSON.stringify(a));
console.log(removeNull(a));

还未实现移除子对象中空属性的功能

posted @ 2023-04-13 21:40  敲可耐的咕魂君  阅读(35)  评论(0编辑  收藏  举报
页脚 HTML 代码 ----