Reputation:
I have this simple function, that returns an array based on a condition:
const operationPerResource = (resource: ResourceTypes): OperationTypes[] => {
const operations = cases[resource] || cases.default;
return operations;
};
And I want to use that Function to iterate over an Array of Object with a {labe: string, value: string} type.
So, I create a simple map
:
const resources = transformEnumToArray(ResourceTypes);
const operations = operationPerResource(resources[0].value).map((value: any) => ({
label: value,
value
}));
The above function gives the results only for the first item in the array. I want to iterate over all the items of the Array resources
in our case, and depending on which one I choose, I get back the available operations.
THE PROBLEM:
I have a select-box. Each select-box is populated by resources. Every time, I select a resource, I want to print the correct output. So, I used the operationPerResource
function to return the available operations for each resource:
But, the resources are an Array of Objects, so, I need to iterate over them, in order to get back the correct Operations every time:
exmaple:
Resource: Name1 => Operations for Name1[3 Items]
Resource: Name2 => Operations for Name2[2 Items]
Resource: Name3 => Operations for Name3[5 Items]
And so on and so on. If I click on a specific resoure I get back the expected results each time. I just want to make it dynamic..
I only want to print the results of each resource not all of the results together.
I am kinda stuck here. Any help will be appreciated.
Upvotes: 1
Views: 3432
Reputation: 350
It seems like you want to iterate over all the resource types then aggregate all the mapping results from each of those. As a result you essentially are creating an array of arrays. You can flatten these following logic similar to:
const resourceTypes = transformEnumToArray(ResourceTypes);
const operations = [];
resourceTypes.forEach(resourceType => {
const operationsForResource = operationsPerResource(resourceType.value);
Array.prototype.push.apply(operations, operationsForResource.map((value: any) => ({
label: value,
value
})));
});
operations
will then contain all of the map results aggregated in one array.
Upvotes: 0
Reputation: 171679
I think what you want is to map resources
array with a nested map() of array returned from operationPerResource()
const operations = resources.map((r) => {
return operationPerResource(r.value).map((value: any) => ({
label: value,
value
})
})
})
Upvotes: 1