代码之家  ›  专栏  ›  技术社区  ›  silkfire thezar

将空值或假值强制转换为未定义值

  •  0
  • silkfire thezar  · 技术社区  · 5 年前

    我想将任何falsy值转换为未定义的值,这样就不会将特定属性添加到生成的JSON对象中。

    const response = {
      myValue: 'someString',
      errorMessage: error && 'An unexpected error occurred'
    };
    

    在这里,我想要 errorMessage 要解析到的属性 undefined error 对象是 null . 不幸的是,如果没有错误 错误消息 财产变成 无效的 而不是 未定义 ,导致它包含在最终对象中。是否有语法可以防止这种情况?

    3 回复  |  直到 5 年前
        1
  •  4
  •   silkfire thezar    5 年前

    你可以附加 || undefined 在声明的最后,它应该可以正常工作。

    const error = null
    const response = {
      myValue: 'someString',
      errorMessage: error && 'An unexpected error occurred' || undefined
    };
    console.log(JSON.stringify(response))
        2
  •  1
  •   Dan Starns    5 年前

    使用三元

    const error = false;
    
    const response = {
      myValue: 'someString',
      errorMessage: error ? 'An unexpected error occurred' : undefined
    };
    
    const json = JSON.stringify(response);
    
    console.log(json)
        3
  •  0
  •   Shirish Maharjan    5 年前
     const response = {
          myValue: 'someString',
          errorMessage: error?error:undefined
        };