
本文介绍使用 javascript 递归遍历并移除 json 中所有值为 null 或空字符串 "" 的键,并进一步剔除因此变为“全空”的嵌套对象(如 image: {src: null, name: null, alignment: null}),最终得到精简、语义纯净的 json 结构。
要真正实现题设目标——不仅过滤掉 null/empty 值,还要删除因过滤而变为空对象的嵌套结构(如整个 image 对象)——仅靠 JSON.stringify 的 replacer 是不够的:它能跳过 null 和 "",但无法判断某个对象在剔除这些键后是否已成空对象({}),因而无法向上递归裁剪。
✅ 正确解法是:手写递归清理函数,逐层处理,对每个对象执行「过滤键 → 递归清理子值 → 若结果为空对象则返回 undefined」三步逻辑。
以下是完整、健壮的实现:
function cleanNullish(obj) {
if (obj === null || obj === undefined) return undefined;
// 处理数组:递归清理每一项,并过滤掉 undefined 项
if (Array.isArray(obj)) {
return obj
.map(item => cleanNullish(item))
.filter(item => item !== undefined);
}
// 处理普通对象
if (typeof obj === 'object') {
const cleaned = {};
let hasContent = false;
for (const [key, value] of Object.entries(obj)) {
const cleanedValue = cleanNullish(value);
// 仅保留非 undefined 的键值对
if (cleanedValue !== undefined) {
cleaned[key] = cleanedValue;
hasContent = true;
}
}
// 若清理后无任何有效键值,则整层对象应被移除(返回 undefined)
return hasContent ? cleaned : undefined;
}
// 基础类型(string, number, boolean):仅当为 null 或 "" 时剔除;其他原样保留
return obj === null || obj === '' ? undefined : obj;
}
// 使用示例
const input = {
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"text": null,
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"definition": null
},
"GlossSee": "markup",
"window": {
"title": "Sample Konfabulator Widget",
"description": ""
}
}
}
},
"image": {
"src": null,
"name": null,
"alignment": null
},
"text": {
"data": "Click Here",
"size": null,
"style": "bold",
"name": "text1",
"hOffset": "",
"vOffset": "",
"alignment": "center",
"onMouseUp": null
}
}
};
const result = cleanNullish(input);
console.log(JSON.stringify(result, null, 2));? 关键特性说明:
- ✅ 支持任意深度嵌套对象与数组;
- ✅ 自动识别并删除「全空对象」(如 image)和「全空数组」;
- ✅ 严格区分 ""(空字符串)、null、undefined,统一剔除;
- ✅ 保留 0、false、" "(含空格字符串)等有业务意义的值(若需也过滤空白字符串,可将条件改为 !value && value !== 0 && value !== false);
- ✅ 返回新对象,不修改原始数据(纯函数式)。
⚠️ 注意事项:
- JSON.stringify(..., replacer) 方案无法删除空对象,它只跳过键,却仍会保留 {} 结构(例如 "image": {}),不符合题设输出要求;
- 若需兼容旧环境(如 IE),请避免使用 Object.entries,改用 for...in + hasOwnProperty;
- 对超大 JSON,请注意递归深度限制,必要时可转为栈式迭代实现。
通过该函数,输入 JSON 将精准产出题设所求的精简结构:image 被彻底移除,GlossDef 和 window 中的空字段被剥离,text 中无效键被清除,语义更清晰、体积更小、后续解析更安全。










