DiPix
DiPix

Reputation: 6083

How to set default value for NULL property in TypeScript

I'm trying to set default value for all my NULL objects. Here's what I have

private setDisplayAmount(summaries: summary[]): void {
    summaries.map(t => {
        // do some magic, and then...
        this.setDefaultValueForEmptyAmounts(t);
    });
}

private setDefaultValueForEmptyAmounts(summary: Summary): void {
    Object.values(summary.displayAmounts).map(property => property || 0);
}

I've no idea why setDefaultValueForEmptyAmounts doesn't work properly...

This will work but is less esthetic:

private setDisplayAmount(summaries: summary[]): void {
    summaries.map(t => {
        // do some magic, and then...
        t.displayAmounts = {
            OneAmount: t.oneAmt || 0,
            TwoAmount: t.twoAmt || 0,
            // ... for all properties
        };

    });
}

Upvotes: 0

Views: 2013

Answers (1)

Anouar
Anouar

Reputation: 120

When using map operations, you should always return something. But you could use forEach.

summaries.forEach(summary => {
    Object.keys(summary).forEach(key => {
    summary[key] = summary[key] || 0;
    });
});

Upvotes: 2

Related Questions