Reputation: 6436
I am using mourner/suncalc to get information about our sun. I want to get all the times where the position of our sun will be, using SunCalc.getTimes()
, but to prevent using "miles long" variables, I want to call each data through a function.
I am thinking about something like this:
function sun_times(string) {
var sun_times = SunCalc.getTimes(new Date(), 54.528486, -7.569268);
return (sun_times.string.getHours().toString() < 10 ? '0' + sun_times.string.getHours().toString() : sun_times.string.getHours().toString());
}
console.log(sun_times('dawn'));
This example returns (as expected) TypeError: sun_times.string is undefined
.
Instead of entering sun_times.dawn.getHours().toString() + ':' + sun_times.dawn.getMinutes().toString()
for every time at dawn, dusk, golden hour, nadir, nautical dawn, and so on, I just want to enter the function and then the data I want to print out, for an example sun_times('dawn')
.
How can I accomplish this the best way?
Upvotes: 0
Views: 274
Reputation: 5964
A JavaScript object works like a dictionary structure. We use the []
indexing operator to access properties only known at runtime. It's like array access, but with strings instead of numbers.
function sun_times(string) {
var sun_times = SunCalc.getTimes(new Date(), 54.528486, -7.569268);
return (sun_times[string].getHours().toString() < 10 ? '0' + sun_times[string].getHours().toString() : sun_times[string].getHours().toString());
}
Upvotes: 1