問題描述:
將對象中的空字段刪掉,比如這樣的一個對象:
const obj = {
name: 'wise',
age: 0,
info: '',
key1: null,
key2: undefined,
}
處理成爲:
obj = {
name: 'wise',
age: 0,
}
解決方案:
/**
* 深度刪除對象/數組中的空字段
* @param {Object} obj 目標對象
* @param {Array} except 必須排除的字段名的集合,這些字段不論結果,直接捨棄
*/
function CleanEmptyKey(obj, except = ['key']) {
if (typeof obj !== 'object') { // 兼容對象和數組
return obj;
}
const res = Array.isArray(obj) ? [] : {};
for (const key in obj) {
// 如果是需要排除的字段,直接捨棄
if (except && except.includes(key)) continue;
// 有值或值爲0,則保留鍵值對
if (obj[key] || obj[key] === 0) {
res[key] = CleanEmptyKey(obj[key]);
}
}
return res;
};