My app is reading in multiple Json files in Typescript populate select boxes, but I want to avoid wet (write everything twice) code and keep things dry (don't repeat yourself). I originally had unique functions for each json file, as they each have different values and need to be parsed differently, but I instead one to make one function that can be called from my main class that will do the reading and parsing into an array and return.
For example, my Countries Json looks like this:
{
"Countries": {
"country": [
{
"_CountrySEQ": "0",
"_CountryCodeDesc": "UNITED STATES",
"_CountryCode": "USA"
},
{
"_CountrySEQ": "1",
"_CountryCodeDesc": "CANADA",
"_CountryCode": "CAN"
},
, , ,
}
}
I would need it to be parsed into a key/value array and looks like this:
[
{
key:'USA',
value:'UNITED STATES'
},
{
key:'CAN',
value:'CANADA'
}
. . .
]
But I have a statesjson that looks like this:
{
"States": {
"state": [
{
"_State": "(cantons) Aargau",
"_CountryCode": "CHE"
},
{
"_State": "Abruzzi",
"_CountryCode": "ITA"
}
. . .
]
}
}
And needs to be parsed out to look like this:
[
{
key:'CHE',
value:'(cantons) Aargau'
},
{
key:'ITA',
value:'Abruzzi'
}
. . .
]
Is there a way to do this a modular as possible? Like a single function to handle this? Are arrays of classes or interfaces the best solution? And if so, how do I properly implement them?
This function handles both datasets.
const parser = (dataset) => {
const [first, second, index1, index2] =
dataset.Countries ?
["Countries", "country", 2, 1] : ["States", "state", 0, 1];
return dataset[first][second].map(item => {
return {
key1: Object.values(item)[index1],
key2: Object.values(item)[index2],
}
});
};
parser(Countries);
parser(States);