
本文介绍使用 javascript 递归遍历并移除 json 中所有值为 `null` 或空字符串 `''` 的键值对,同时自动删除因此变为空对象的嵌套结构,实现深度精简。
在实际开发中,后端返回的 JSON 数据常包含大量冗余字段(如 null、空字符串 ""),不仅增加传输体积,还可能干扰前端逻辑判断。单纯用 JSON.stringify(..., replacer) 只能过滤掉 null/"" 值,但无法自动删除因此产生的空对象(如 "image": {})。要达到题干中“彻底移除全空对象”的效果,需结合递归清理 + 空对象检测。
以下是专业、健壮的解决方案:
✅ 推荐方案:递归清理 + 后置空对象裁剪
function cleanNullish(obj) {
if (obj === null || typeof obj !== 'object') return obj;
// 1. 深度遍历:移除 null / undefined / 空字符串
const cleaned = Object.fromEntries(
Object.entries(obj)
.map(([k, v]) => [k, cleanNullish(v)]) // 递归处理子值
.filter(([, v]) => v !== null && v !== undefined && v !== '')
);
// 2. 关键步骤:若 cleaned 是对象且无自有属性,则返回 undefined(触发上层过滤)
if (typeof cleaned === 'object' && cleaned !== null && Object.keys(cleaned).length === 0) {
return undefined;
}
return cleaned;
}
// 使用示例
const input = { /* 题干中的原始 JSON */ };
const result = cleanNullish(input);
console.log(JSON.stringify(result, null, 2));? 为什么 JSON.stringify 的 replacer 不够用?
题干答案中仅用 JSON.stringify(data, (k,v) => v === null || v === '' ? undefined : v) 存在两个关键缺陷:
- ❌ 不递归处理空对象:"image": {"src": null, "name": null} → 清理后变为 "image": {},但 {} 仍保留在结果中;
- ❌ 无法识别空数组/空对象语义:[]、{} 若本身是有效业务值(非冗余),不应被误删 —— 本方案通过显式 Object.keys().length === 0 判断,确保只剔除因字段清除而被动变空的对象。
⚠️ 注意事项
- 该函数不修改原对象,返回全新精简后的深拷贝;
- 支持任意嵌套层级(对象、数组、混合结构),数组中 null/"" 元素同样被过滤;
- 若需保留 0、false、"0" 等falsy 但非空值,当前逻辑已默认兼容(仅排除 null、undefined、"");
- 如需扩展支持 NaN 或空白字符串(如 " "),可在 filter 条件中增强判断:v?.trim() !== ''。
✅ 最终效果验证
输入中 "image": {src: null, name: null, alignment: null} → 完全消失;
"GlossDef": {para: "...", definition: null} → 变为 {para: "..."};
"window": {title: "...", description: ""} → 变为 {title: "..."};
完全匹配题干期望输出。
此方法兼顾简洁性与鲁棒性,是生产环境推荐的 JSON 轻量化标准实践。









