Is there a way to add a variable to a constructor when fetching data?

Viewed 73

Basically, I'm making a statistics website where I use the Fetch API to get data and display it on my page. The thing is that the API I'm using has a hefty amount of data, all with pretty similar names too. For example, there's different type of gamemodes and could show up as: build-casual-wins: #; archer-casual-wins: #; I am using a constructor and I was wondering if there was a way to set a variable in the constructor to make it easier?

For example:

    constructor(buildUHCWins, buildUHCLosses, buildCasualWS, buildCasualBestWS, buildUHCWinsComp, buildUHCLossesComp, buildCompWS, buildCompBestWS) {

    }
}

I'm tired of having it setup with how repetitive this is. Is there a way to just do something where it would show up like:

    constructor(${variable}wins) {
        this.${variable}wins = wins;
    }
}

Or something like that?

EDIT:

let buildCompBestWS = data.response["builduhc-competitive-best-winstreak"];
let stats = new userStats(buildUHCWins, buildUHCLosses, buildCasualWS, buildCasualBestWS, buildUHCWinsComp, buildUHCLossesComp, buildCompWS, buildCompBestWS);

This is how I have my other file setup where I'm calling the constructor to use the data I get from the API and display it on my page. I'm wondering how to minimalize that because as you see, I have multiple parameters in the constructor and have to call to the API for data.response.${gamemode type}.

1 Answers

You could pass in an associative array/object instead of each individual record

let records = {buildUHCWins:"...", buildCasualWS:"...",...}

constructor(records)
{
    this.records = records;
}

if you wanted to have the object records as direct members you could do this


constructor(records)
{
    for (key in records) {
        this[key] = records[key];
    }
}

then you could still access foo.buildUHCWins

Related