删除属性值为 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: {}}