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