我正在尝试将对象添加到Fee对象数组中。收费对象的结构如下
export interface DomicileFee {
fieldInfo: FieldInfo;
value?: number;
}
我尝试添加对象的方法如下
private filterFees(fees: BackendDto.DomicileFee[]) {
if (fees !== null) {
const fee = 'Fee';
this.totalFees = 0;
this.captiveAssumptionsFees = fees.filter(a => a.fieldInfo.key.endsWith(fee) === false );
fees.filter(a => a.fieldInfo.key.endsWith(fee)).forEach(a => { this.totalFees += a.value; });
//fees.push(this.totalFees);
}
}
我需要能够添加一个新对象并将this.totalFees分配给它。 例如
fieldInfo : 'genExp' and value : this.totalFees
我试过了,它可以工作,但是在运行那段代码时它会不断添加。我只需要添加一次
fees.push({ fieldInfo: {key: 'generalExpenses' } as FieldInfo, value: this.totalFees });
答案 0 :(得分:0)
由于使用特定键添加了总对象,因此只需检查一下是否已添加即可。这样,您可以添加不存在的元素,但是如果存在则可以替换数据。
private filterFees(fees: BackendDto.DomicileFee[]) {
if (fees !== null) {
const fee = 'Fee';
this.totalFees = 0;
this.captiveAssumptionsFees = fees.filter(a => a.fieldInfo.key.endsWith(fee) === false );
fees.filter(a => a.fieldInfo.key.endsWith(fee)).forEach(a => { this.totalFees += a.value; });
const existingData = fees.find(item => item.fieldInfo.key === "generalExpenses");
if (existingData) {
existingData.value = this.totalFees;
} else {
fees.push({ fieldInfo: {key: 'generalExpenses' } as FieldInfo, value: this.totalFees });
}
}
}