Home > Mobile >  how to store the value of a key for a object and pass it to the function which is a value of another
how to store the value of a key for a object and pass it to the function which is a value of another

Time:06-23

"sideCardInfo": {
                        "title": "Hospital Admission",
                        "reportTitle": "Hospital Admission Report",
                        "subTitle": "Per 1000 Members",
                        "dateFilter": [
                            {
                                "date": previousYearRange,
                                "value": calculateAverage(allInsightData.map(obj => Number(obj.hospital_admissions_cnt_py))),
                            },
                            {
                                "date": currentYearRange,
                                "value": calculateAverage(allInsightData.map(obj => Number(obj.hospital_admissions_cnt))),
                            }
                        ],
                        "percentage": calculatePercentage( calculateAverage(allInsightData.map(obj => Number(obj.hospital_admissions_cnt_py))), calculateAverage(allInsightData.map(obj => Number(obj.hospital_admissions_cnt)))),
                        "tooltipText": ""
                    },

In the above object inside dateFilter for value i am using a calculateAverage function to get the value i need to pass the same value as parameter for calculatePercentage which is a value for percentage key in the same object how to store the calculateAverage at dateFilter and pass it to calculatePercentage so that i can avoid calculating average two times

CodePudding user response:

Simple, use variables to store those results.

E.g

const prevYearAvg = calculateAverage(allInsightData.map(obj => Number(obj.hospital_admissions_cnt_py)))
const currYearAvg = calculateAverage(allInsightData.map(obj => Number(obj.hospital_admissions_cnt)))

    "sideCardInfo": {
        "title": "Hospital Admission",
        "reportTitle": "Hospital Admission Report",
        "subTitle": "Per 1000 Members",
        "dateFilter": [
            {
                "date": previousYearRange,
                "value": prevYearAvg,
            },
            {
                "date": currentYearRange,
                "value": prevYearAvg,
            }
        ],
        "percentage": calculatePercentage(prevYearAvg, prevYearAvg),
        "tooltipText": ""
    }

CodePudding user response:

To access the properties from within the object you can use getters.

const dataset = {
  sideCardInfo: {
    title: "Hospital Admission",
    reportTitle: "Hospital Admission Report",
    subTitle: "Per 1000 Members",
    dateFilter: [
      {
        date: 1,
        value: 1
      },
      {
        date: 2,
        value: 2
      }
    ],
    get percentage(){
      return this.dateFilter[0].value   this.dateFilter[1].value;
    },
    tooltipText: ""
  }
};

console.log(dataset.sideCardInfo.percentage);

  • Related