Not sure how 'smart' of an idea this is but I really wanted to experiement with Vue and Javascript and see if I could condense some code a bit (you could say I've done the opposite).
Anways... I have an data object in vue:
eventOptions: {
eventType: {
data: [],
method: 'getEventTypeList',
service: 'ReportEventService',
},
eventSeverity: {
data: [],
service: 'ReportEventService',
method: 'getSeverityList',
},
eventImpact: {
data: [],
service: 'ReportEventService',
method: 'getBusinessImpactList',
},
eventStatus: {
data: [],
service: 'ReportEventService',
method: 'getEventStatusList',
},
},
And I want to loop through it in the following method and create a function like:
ReportEventService.getEventStatusList()
which is referencing an imported javascript file.
async setEventOptions() {
const promises = Object.keys(this.eventOptions).map((key) => {
const { method, service = this.eventOptions[key]
return new Promise(async (resolve, reject) => {
try {
const response = await service[method]();
resolve(response);
} catch (e) {
reject(e);
}
});
});
Promise.all(promises)
.then((responseArray) => {
Object.keys(this.eventOptions).forEach((key, index) => {
this.eventOptions[key]['data'] =
responseArray[index].data;
});
})
.catch((e) => console.log(e));
},
Unfortunately, it's not working.
This line fails:
const callback = service[method]();
Any idea how I can convert two strings to make a function that I can execute? I also understand this undertaking is silly and I can probably just list them out and it would be 10x easier.
I did try:
const func = new Function(`${service}.${method}()`)
The error I get is: TypeError: service[method] is not a function