Declaring array of objects

前端 未结 15 1391
遇见更好的自我
遇见更好的自我 2020-12-02 07:01

I have a variable which is an array and I want every element of the array to act as an object by default. To achieve this, I can do something like this in my code.



        
15条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 07:24

    The below code from my project maybe it good for you

      reCalculateDetailSummary(updateMode: boolean) {
    
        var summaryList: any = [];
        var list: any;
        if (updateMode) { list = this.state.pageParams.data.chargeDefinitionList }
        else {
            list = this.state.chargeDefinitionList;
        }
    
        list.forEach((item: any) => {
            if (summaryList == null || summaryList.length == 0) {
                var obj = {
                    chargeClassification: item.classfication,
                    totalChargeAmount: item.chargeAmount
                };
                summaryList.push(obj);
    
            } else {
                if (summaryList.find((x: any) => x.chargeClassification == item.classfication)) {
                    summaryList.find((x: any) => x.chargeClassification == item.classfication)
                        .totalChargeAmount += item.chargeAmount;
                }
            }
        });
    
        if (summaryList != null && summaryList.length != 0) {
            summaryList.push({
                chargeClassification: 'Total',
                totalChargeAmount: summaryList.reduce((a: any, b: any) => a + b).totalChargeAmount
            })
        }
    
        this.setState({ detailSummaryList: summaryList });
    }
    

提交回复
热议问题