js 删除对象中所有值为undefined、null、false、0、NaN、""的属性


 

删除属性值为 null、undefined、""、0、NaN、false字段

let obj={
    a:'a',
    b:null,
    c:'c',
    d: undefined,
    e: '',
    f: 0,
    g: NaN,
    h: false
}

var removePropertyOf=function(obj){
    Object.keys(obj).forEach(item=>{
        if(!obj[item])  delete obj[item]
    })
    return obj;
}
removePropertyOf(obj);
console.log(obj); // => {a: "a", c: "c"}

删除属性值为 null、undefined、""、NaN、false字段 排除 0

// 排除 0 不删除
let obj={
    a:'a',
    b:null,
    c:'c',
    d: undefined,
    e: '',
    f: 0,
    g: NaN,
    h: false,
    i: '0',
    j: function(){},
    k: {},
    l: []
}

var removePropertyOf=function(obj){
    Object.keys(obj).forEach(item=>{
        if(obj[item] + '' === "undefined" || obj[item] + '' === "null" || obj[item] + '' === "" ||  obj[item] + '' === 'NaN' || obj[item] + '' === "false" )  delete obj[item]
    })
    return obj;
}
var aa = removePropertyOf(obj)
console.log(aa); // => {a: "a", c: "c", f: 0, i: "0", j: ƒ (), k: {}}

删除属性值为 null、undefined、""、NaN字段 排除 0、false

let obj={
    a:'a',
    b:null,
    c:'c',
    d: undefined,
    e: '',
    f: 0,
    g: NaN,
    h: false,
    i: '0',
    j: function(){},
    k: {},
    l: []
}

var removePropertyOf=function(obj){
    Object.keys(obj).forEach(item=>{
        if(obj[item] + '' === 'undefined' || obj[item] + '' === "null" || obj[item] + '' === "" ||  obj[item] + '' === 'NaN')  delete obj[item]
    })
    return obj;
}
var aa = removePropertyOf(obj)
console.log(aa);  // => {a: "a", c: "c", f: 0, h: false, i: "0", j: f (), k: {}}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM