[英]How to set default value for NULL property in TypeScript
I'm trying to set default value for all my NULL
objects. 我正在尝试为所有
NULL
对象设置默认值。 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... 我不知道为什么
setDefaultValueForEmptyAmounts
无法正常工作...
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
};
});
}
When using map operations, you should always return something. 使用地图操作时,应始终返回一些内容。 But you could use forEach.
但是您可以使用forEach。
summaries.forEach(summary => {
Object.keys(summary).forEach(key => {
summary[key] = summary[key] || 0;
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.