Search code examples
javascriptangulartypescriptjavascript-objects

How can I check if a value is undefined in order to not add it as a object field?


I am working on an Angular application and I have the following doubt using TypeScript related how to correctly avoid to insert a field into an object if the value is undefined.

In my code I am creating an object in this way:

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,
};

The problem is that some fields can have undefined value. In this case the field have not to be inserted into my aestheticEvaluation object.

So for example, if the aestheticEvaluationInfo.get('altezza').value value is undefined this "altezza" field is not inserted in the object

I know that I can use an if statment in order to check if the value of each fields is null and in this case avoid to insert the object but in this way the code will be a lot more redundant. Exist a way to do directly into my object definition?


Solution

  • So I have two solutions in my mind you may choose the one the suits you better.

    1. Default value instead of undefined, in this case, you set the value as the default value (ie. empty string '', or zero for numbers, etc..).
    const object = {
        key: anotherObject?.attribute || ''
    };
    
    1. Set the object values then clean the object at last (remove undefined values):
    const object = { key: value };
    
    Object.keys( object ).forEach( key => {
        if ( !object[key] ) delete object[key];
    } );
    

    Please let me know if I'm misunderstanding anything.