【问题标题】:How can I check if a value is undefined in order to not add it as a object field?如何检查值是否未定义以便不将其添加为对象字段?
【发布时间】:2021-09-04 00:26:25
【问题描述】:

我正在开发一个 Angular 应用程序,我对使用 TypeScript 有以下疑问,如果值未定义,如何正确避免将字段插入对象。

在我的代码中,我以这种方式创建了一个对象:

let aestheticEvaluation: AestheticEvaluation = {
    "altezza": aestheticEvaluationInfo.get('altezza').value,
    "peso": aestheticEvaluationInfo.get('peso').value,
    "phototype": aestheticEvaluationInfo.get('phototype').value.name,
    "photoaging": aestheticEvaluationInfo.get('photoaging').value.name,
    "comedoni": aestheticEvaluationInfo.get('comedoni').value.name,
    "varici": aestheticEvaluationInfo.get('varici').value.name,
    "rugheGlifiche": aestheticEvaluationInfo.get('rugheGlifiche').value.name,
    "accentuazioneDeiPigheNasogeniene": aestheticEvaluationInfo.get('accentuazioneDeiPigheNasogeniene').value.name,
    "gradoAgingCollo": aestheticEvaluationInfo.get('gradoAgingCollo').value.name,
    "occhiaie": aestheticEvaluationInfo.get('occhiaie').value.name,
    "borse": aestheticEvaluationInfo.get('borse').value.name,
    "ipotoniaTerzoInferiore": aestheticEvaluationInfo.get('ipotoniaTerzoInferiore').value.name,
    "cellulite": aestheticEvaluationInfo.get('cellulite').value.name,
    "cicatriciIpertroficheCheloidi": aestheticEvaluationInfo.get('cicatriciIpertroficheCheloidi').value,
    "luceDiWood": aestheticEvaluationInfo.get('luceDiWood').value,
    "notes": aestheticEvaluationInfo.get('notes').value,
};

问题是某些字段可能具有 undefined 值。在这种情况下,该字段不必插入到我的 aestheticEvaluation 对象中。

例如,如果 aestheticEvaluationInfo.get('altezza').value 值为 undefined,则此 "altezza" 字段不是插入对象

我知道我可以使用 if 语句来检查每个字段的值是否为 null 并且在这种情况下避免插入对象但这样代码会很多更多余。有没有办法直接进入我的对象定义?

【问题讨论】:

标签: javascript angular typescript javascript-objects


【解决方案1】:

创建一个函数,在创建对象之前检查对象中的每个值,如下所示。

// data structure of `aestheticEvaluationInfo` seems to be a map
let aestheticEvaluationInfo = new Map();
aestheticEvaluationInfo.set('altezza', { value: { name: 'altezza'}});
aestheticEvaluationInfo.set('peso', { value: { name: 'peso'}});
.
.
.
// rest of the fields
aestheticEvaluationInfo.set('notes', undefined);


function createObjWithValues(data) {
  let obj = {};
  for (const [key, value] of data.entries()) {
    if (value) obj[key] = value.value.name;
  }
  return obj;
}

console.log(createObjWithValues(aestheticEvaluationInfo));

【讨论】:

    【解决方案2】:

    这是一种与其他解决方案略有不同的方法,但允许您只声明每个条件一次,并快速更改获取值的方法,因为它只在一行上。

    let aestheticEvaluationCriteria: string[] = [
      "altezza",
      "peso",
      "phototype",
      "photoaging",
      "comedoni",
      "varici",
      "rugheGlifiche",
      "accentuazioneDeiPigheNasogeniene",
      "gradoAgingCollo",
      "occhiaie",
      "borse",
      "ipotoniaTerzoInferiore",
      "cellulite",
      "cicatriciIpertroficheCheloidi",
      "luceDiWood",
      "notes",
    ]
    
    let aestheticEvaluation: AestheticEvaluation = {}
    aestheticEvaluationCriteria.forEach((criteria)=>{
      const value = aestheticEvaluationInfo.get(criteria).value
      if (value){
        aestheticEvaluation[criteria] = value
      }
    })
    //aestheticEvaluation is now filled as specified
    console.log(aestheticEvaluation)
    

    【讨论】:

      【解决方案3】:
        let aestheticEvaluation: AestheticEvaluation = {
         "altezza": aestheticEvaluationInfo.get('altezza').value,
         "peso": aestheticEvaluationInfo.get('peso').value,
         ....  so on
        }
      
      
        for(let key in aestheticEvaluation)
        { 
         if(!aestheticEvaluation[key]) 
          delete aestheticEvaluation[key]
         }
      
          !aestheticEvaluation[key] = This will include all falsy values such as 
          null,undefined,0,''.
          If you just want to check for undefined value you can use 
         for(let key in aestheticEvaluation)
          { 
           if(typeof aestheticEvaluation[key] === "undefined") 
            delete aestheticEvaluation[key]
          }
      

      【讨论】:

      • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
      【解决方案4】:

      所以我想到了两种解决方案,您可以选择更适合您的一种。

      1. 默认值而不是 undefined,在这种情况下,您将值设置为默认值(即空字符串 '',或数字为零等)。
      const object = {
          key: anotherObject?.attribute || ''
      };
      
      1. 设置对象值,最后清理对象(删除未定义的值):
      const object = { key: value };
      
      Object.keys( object ).forEach( key => {
          if ( !object[key] ) delete object[key];
      } );
      

      如果我有什么误解,请告诉我。

      【讨论】:

        猜你喜欢
        • 2011-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-02
        • 1970-01-01
        • 2014-02-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多