My application compares API data, in my case temperatures. I have written it with a function for each API first like this:
async function prepData(n) {
const a = [];
if ((n == 0)) {
const json = await firstAPI();
for (var i = 0; i <= c; i++) {
a.push(json.shortIntervals[i].temperature.value);
}
console.log(a);
return a;
} else {
const json = await secondAPI();
for (var i = 0; i <= c; i++) {
a.push(
json.properties.timeseries[i].data.instant.details.air_temperature,
);
}
console.log(a);
return a;
}
}
This code works successfully but it has a lot of repeating code, therefore I want to change it.
I have successfully merged the fetching functions and call the API url from a array by passing the "n" witch determines witch API I want to access. Now I am left standing with the problem that I can't access the data in the different locations.
The code currently looks like this:
const dataLocation = ['json.first.api.path', 'json.seccond.api.path']
async function prepData(n) {
const a = [];
const json = await fetching(n);
for (var i = 0; i <= c; i++) {
a.push(dataLocation[n]);
}
console.log(a);
return a;
You can see that I now have the datalocation stored in a array, but I can't "execute" it, if I put the "dataLocation[n]" in directly I add the path as a string to the new array, and with quotes I push the arrayname.
How can I tell Javascript that it should look in the location defined in the array?
Also: "c" is a number that is defined earlier in the code and defines the amount of data accessed from the api´s
if ( n=0 )assigns the value of 0 to n. The result of this assignment is0which will evaluate to false- same asif ( 0 ) {or same asif ( false) {, so that block will never get executed. Useif (n === 0) {