如何用JavaScript递归移除JSON中全空值对象及空键
移除JSON中无效值与空对象的JavaScript实现
要解决递归移除嵌套对象中null/空字符串键,以及所有值均为无效值的空对象问题,可以写一个递归处理函数,遍历并清理数据结构中的无效内容:
核心实现代码
function cleanData(data) { // 处理数组:递归清理每个元素,过滤无效项 if (Array.isArray(data)) { return data .map(item => cleanData(item)) .filter(item => { if (item === null || item === '') return false; if (typeof item === 'object' && Object.keys(item).length === 0) return false; return true; }); } // 处理对象:遍历键值对,仅保留有效内容 if (typeof data === 'object' && data !== null) { const cleanedObj = {}; for (const key in data) { if (Object.prototype.hasOwnProperty.call(data, key)) { const cleanedValue = cleanData(data[key]); // 跳过null、空字符串,以及清理后为空的对象/数组 if (cleanedValue === null || cleanedValue === '') continue; if (typeof cleanedValue === 'object') { if (Array.isArray(cleanedValue) && cleanedValue.length === 0) continue; if (!Array.isArray(cleanedValue) && Object.keys(cleanedValue).length === 0) continue; } cleanedObj[key] = cleanedValue; } } // 若清理后对象为空,返回null让父级过滤 return Object.keys(cleanedObj).length > 0 ? cleanedObj : null; } // 基础类型直接返回(null和空字符串会被父级逻辑过滤) return data; }
使用示例
原始数据
const rawData = { user: "Alice", age: null, description: "", profile: { avatar: { url: null, alt: null }, bio: "喜欢编程", social: { twitter: "", github: null } }, tags: [null, "", "frontend", { name: null }, { category: "JS" }] };
处理后结果
调用cleanData(rawData)后,输出的JSON为:
{ "user": "Alice", "profile": { "bio": "喜欢编程" }, "tags": [ "frontend", { "category": "JS" } ] }
逻辑说明
- 递归遍历:无论是对象还是数组,都会递归处理内部的嵌套结构,确保所有层级的无效值都被清理
- 无效值过滤:直接移除值为
null或空字符串""的键 - 空对象/数组清理:如果某个对象在移除无效键后变成空对象,会被标记为
null,最终被父级过滤;数组中的空对象、空数组、null/空字符串也会被过滤 - 原型安全:遍历对象时使用
hasOwnProperty,避免处理原型链上的属性
内容的提问来源于stack exchange,提问作者mnvbrtn
相关产品推荐
相关产品推荐

