javascript - 我如何检查一个值是否未定义,以避免将其作为对象字段添加?
我正在开发一个 Angular 应用程序,我有以下关于如何在 TypeScript 中正确地避免在值为 undefined 时将字段插入对象的疑问。
在我的代码中,我是通过这种方式创建一个对象的:
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,
};
问题是某些字段可能具有未定义的值。在这种情况下,该字段不应被插入到我的aestheticEvaluation对象中。
例如,如果 aestheticEvaluationInfo.get('altezza').value 的值是 undefined,那么这个 "altezza" 字段不会被插入到对象中
我知道我可以使用 if 语句来检查每个字段的值是否为 null,在这种情况下避免插入对象,但这样代码会更加冗余。有一种方法可以直接在我的对象定义中完成吗?
答案#1
所以我脑子里有两个解决方案,你可以选择更适合你的那个。
- 默认值而不是未定义,在这种情况下,你将值设置为默认值(例如,空字符串'',或者数字为零等)。
const object = {
key: anotherObject?.attribute || ''
};
- 先设置对象的值,然后最后清理对象(移除未定义的值):
const object = { key: value };
Object.keys( object ).forEach( key => {
if ( !object[key] ) delete object[key];
} );
如果我有任何误解,请告诉我。
答案#2
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]
}
