某字段沒有值的時候 后端要求直接干掉此字段探遵,估寫了個方法對數(shù)據(jù)進行處理
//過濾請求參數(shù)中的空字符串,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));