清除对象中没值的数据 unfined、null、[]、{}、''

针对在对空值的定义上
前端:输入框中不输入值就是没值但是实际上输入框绑定了一个字段,不输入值为undefined或''。还有{}、[]、null。

let params = { a: 1, b: undefined, c: '', d: {}, e:[], f: null }

后端:空值就不应该将该值放入参数中。期望的对象是:
let params = { a: 1 }

针对这种情况构建函数处理
function clearEmptyPro(obj) { let curVal = {}; let toString = Object.prototype.toString; for (let key in obj) { let value = https://www.it610.com/article/obj[key]; let type = toString.call(value); if (value || type ==="[object Number]" || type === "[object Boolean]") { switch (type) { case "[object Object]": if (Object.keys(value).length > 0) { curVal[key] = value; } break; case "[object Array]": if (value.length > 0) { curVal[key] = value; } break; default: curVal[key] = value; break; } } } return curVal; }

数据测试
var aa = { a: [], b: {}, c: 0, d: 1, f: null, g: undefined, h: true, i: false, k: '',l: 'ss', m: [1], n: { a: 1 } }; console.log(clearEmptyPro(aa)); // { c: 0, d: 1, h: true, i: false, l: 'ss', m: [1], n: { a: 1 }}

但是当数据中的对象或数组中页含有空值就没办法处理。
var aa = { a: [1, 0, false, undefined, null, '', { a: 1, c: 3 }], b: { a: true, b: false, c: '', d: undefined } }; console.log(clearEmptyPro(aa)); // { a: [1, 0, false, undefined, null, '', { a: 1, c: 3 }], b: { a: true, b: false, c: '', d: undefined } }

【清除对象中没值的数据 unfined、null、[]、{}、''】这时就需要对每个对象和数组进行递归进行处理
function clearEmptyPro(data) { let curVal; let toString = Object.prototype.toString; let dataType = toString.call(data); if (dataType || dataType === "[object Number]" || dataType === "[object Boolean]") { switch (dataType) { case "[object Object]": if (Object.keys(data).length > 0) { let momObj = {}; for (let key in data) { let value = https://www.it610.com/article/clearEmptyPro(data[key]); let valueType = toString.call(value); valueType ==="[object Boolean]" || valueType === "[object Number]" || value ? momObj[key] = value : ""; } curVal = momObj; } else { return; } break; case "[object Array]": if (data.length > 0) { let momValue = https://www.it610.com/article/[]; data.forEach((e) => { let value = https://www.it610.com/article/clearEmptyPro(e); let valueType = toString.call(value); valueType ==="[object Boolean]" || valueType === "[object Number]" || value ? momValue.push(value) : ""; }); momValue.length > 0 ? curVal = momValue : ""; } else { return; } break; case "[object Boolean]": default: curVal = data; break; } } else { return; } return curVal; }

数据测试
var aa = { a: [1, 0, false, undefined, null, '', { a: 1, c: 3 }], b: { a: true, b: false, c: '', d: undefined } } console.log(clearEmptyPro(aa)); // { a: [1, 0, false, { a: 1, c: 3 }], b: { a: true, b: false } }

    推荐阅读