← 中文资源

简体中文版本

用 entries 与 fromEntries 剔除空字段

持久化前递归遍历 Object.entries 并用 Object.fromEntries 重组:null、undefined 与空串一律剔除,0 和 false 是真实值必须保留,数组内的空项同样清理。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

{ id: 'a1', meta: { retry: 0, archived: false, tags: [ 'x', 'y' ] } }
{"id":"a1","meta":{"retry":0,"archived":false,"tags":["x","y"]}}

运行说明

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)));