某字段没有值的时候 后端要求直接干掉此字段,估写了个方法对数据进行处理
//过滤请求参数中的空字符串,null,undefined和空对象
const searchData = {
job: 'teacher',
name: '',
age: null,
sex: undefined,
hobby: [],
under_take_count: {
target_type: 0,
target_count_from: '',
target_count_end: '',
},
under_take: {
target_count_from: '',
target_count_end: '',
},
};
function handleData(data) {
const keys = Object.keys(data);
if (keys.length > 0) {
keys.forEach(currentKey => {
const currentVal = data[currentKey];
//处理值为对象的结构
if (!Array.isArray(currentVal) && (currentVal instanceof Object) && Object.keys(currentVal).length > 0) {
const objeVal = handleData(currentVal);
if (Object.keys(objeVal).length > 0) {
data[currentKey] = objeVal;
} else {
//删除空对象
delete data[currentKey];
}
} else {
if (['', null, undefined].includes(currentVal)) {
delete data[currentKey]
}
}
})
}
return data;
};
console.log(handleData(searchData));
//群里大佬说用for in 直接处理然后赋值给新的json
const searchData2 = {
job: 'teacher',
name: '',
age: null,
sex: undefined,
hobby: [],
under_take_count: {
target_type: 0,
target_count_from: '',
target_count_end: '',
},
under_take: {
target_count_from: '',
target_count_end: '',
},
};
function handleData2(data) {
const newData = {};
for (key in data) {
// ***** if 判断一下子解决了 null undefined ''三种情况,可是也会把值为0的过滤掉
if (data[key]) {
//处理值为对象的结构
if (!Array.isArray(data[key]) && (data[key] instanceof Object) && Object.keys(data[key]).length > 0) {
const objeVal = handleData2(data[key]);
if (Object.keys(objeVal).length > 0) {
newData[key] = objeVal;
} else {
//删除空对象
delete newData[key];
}
} else {
newData[key] = data[key]
}
}
}
return newData;
}
console.log(handleData2(searchData2));