I want to create a smarter way of coding of the following example. Important is that each loop (for activeFilters) needs to be fully done, before we want to return the filtersTest.
JavaScript
x
29
29
1
const createFilters = async () => {
2
const filtersTest = [] as any
3
4
// Only create active filters by checking count.
5
const activeFilters = getComponentFilter.value.filter(function(item) {
6
if (item.items) {
7
return item.items.some((obj) => obj.count)
8
}
9
});
10
11
// Loop through the active filters and push arrays into the object.
12
for(let i = 0 ; i < activeFilters.length; i++) {
13
14
const options = await createFilterOptions(activeFilters[i].id, activeFilters[i].items);
15
16
const array = {
17
defaultValue: null,
18
id: activeFilters[i].id,
19
value: 'nee',
20
label: activeFilters[i].label,
21
options: options,
22
}
23
24
filtersTest.push(array)
25
}
26
27
return filtersTest;
28
}
29
Advertisement
Answer
First of all, it should be clear that createFilters
is not going to return the array, but a promise that will eventually resolve to that array.
With that in mind, you can reduce your code a bit, using Promise.all
, the ?.
operator, destructuring parameters, and shorthand property names in object literals:
JavaScript
1
14
14
1
const createFilters = () => Promise.all(
2
getComponentFilter.value.filter(({items}) =>
3
items?.some((obj) => obj.count)
4
).map(({id, label, items}) =>
5
createFilterOptions(id, items).then(options => ({
6
defaultValue: null,
7
id,
8
value: 'nee',
9
label,
10
options
11
}))
12
)
13
);
14