You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅当值非Null且非Undefined时在JSON对象中添加属性?

在JavaScript中仅当值非null/undefined时设置对象属性的最佳方式

下面是几种实用的实现方式,根据你的场景选择即可:

1. 基础条件判断(直观易懂)

先创建空对象,再通过条件判断逐个添加符合要求的属性,兼容所有JS环境:

var test = {};
// != null 可同时排除null和undefined两种情况
if (object.email != null) {
  test.email = object.email.toString();
}
if (object.phone != null) {
  test.phone = object.phone.toString();
}

2. ES6对象展开运算符(简洁优雅)

利用ES6的展开特性,一行式构建对象,适合现代JS项目:

var test = {
  // 条件为真时展开对应属性对象,为假时返回false,展开操作不会生效
  ...(object.email != null && { email: object.email.toString() }),
  ...(object.phone != null && { phone: object.phone.toString() })
};

3. Object.assign合并(ES6+)

通过Object.assign将符合条件的属性合并到目标对象,逻辑清晰:

var test = Object.assign({},
  object.email != null ? { email: object.email.toString() } : {},
  object.phone != null ? { phone: object.phone.toString() } : {}
);

4. 封装工具函数(多属性场景高效)

如果需要处理大量属性,封装工具函数可以减少重复代码,提升可维护性:

// 工具函数:仅当源属性非null/undefined时,添加到目标对象(支持值转换)
function addValidProp(target, source, prop, transform) {
  if (source[prop] != null) {
    target[prop] = transform ? transform(source[prop]) : source[prop];
  }
}

var test = {};
addValidProp(test, object, 'email', val => val.toString());
addValidProp(test, object, 'phone', val => val.toString());

关键注意点

  • 使用!= null是因为它能同时匹配null和undefined,比分开写x !== null && x !== undefined更简洁。
  • 如果你的需求是排除所有假值(比如空字符串、0等),可以把判断条件改成if (object.email),但要注意这会过滤掉合法的假值(比如0作为电话号码的情况)。

内容的提问来源于stack exchange,提问作者Joshua

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 18:40:35