运行说明
strip 递归遍历载荷:数组先 map 后 filter,普通对象走 Object.entries,剔除 null、undefined 与空串后用 Object.fromEntries 重建。meta 里的 retry 0 与 archived false 是真实值,全部保留。
tags 数组丢掉空串与 null,保留 x 与 y;嵌套的 label: undefined 从打印的 JSON 中消失。标量原样通过——可见变化只有 id 与清理后的 meta 结构。
要点提示
- 0 与 false 必须留在过滤之后——它们是有意义的值。
- 数组与对象逐层套用同一条规则。
核心语句
.filter(([, v]) => v !== null && v !== undefined && v !== '')
代码示例
// Plain JSON data only: recursively drop null, undefined and empty strings,
// while 0 and false must survive because they are real values
const strip = (value) => {
if (Array.isArray(value)) {
return value
.map(strip)
.filter((item) => item !== null && item !== undefined && item !== '');
}
if (value !== null && typeof value === 'object') {
return Object.fromEntries(
Object.entries(value)
.filter(([, v]) => v !== null && v !== undefined && v !== '')
.map(([key, v]) => [key, strip(v)]),
);
}
return value;
};
const payload = {
id: 'a1',
note: null,
meta: { retry: 0, archived: false, label: undefined, tags: ['x', '', null, 'y'] },
};
console.log(strip(payload));
console.log(JSON.stringify(strip(payload)));