I am using the map function with an if statement that doesn’t end in else. I have to be strict that only the defined recourseTypes are shown.
in eslint I get an error on my => as it doesn’t end in an else
Array.prototype.map() expects a value to be returned at the end of arrow function.
Is there a correct way to write this?
Code:
JavaScript
x
54
54
1
routes: async () => {
2
const apiURL = process.env.BASE_URL
3
const response = await axios.get(`${apiURL}/urls`)
4
const { data: resources } = response.data
5
const urlModule = resources.map((resource) => {
6
const { resourceType } = resource
7
8
if (resourceType === 'brand') {
9
return {
10
url: `/${resource.url}`,
11
changefreq: 'weekly',
12
priority: 0.9,
13
}
14
} else if (resourceType === 'product') {
15
return {
16
url: `/${resource.url}`,
17
changefreq: 'monthly',
18
priority: 0.8,
19
}
20
} else if (resourceType === 'category') {
21
return {
22
url: `/${resource.url}`,
23
changefreq: 'weekly',
24
priority: 0.7,
25
}
26
} else if (resourceType === 'document') {
27
return {
28
url: `/${resource.url}`,
29
changefreq: 'weekly',
30
priority: 0.6,
31
}
32
}
33
})
34
35
return [
36
{
37
url: '/',
38
changefreq: 'daily',
39
priority: 1,
40
},
41
{
42
url: '/account',
43
changefreq: 'daily',
44
priority: 1,
45
},
46
{
47
url: '/account/order-history',
48
changefreq: 'daily',
49
priority: 1,
50
},
51
urlModule,
52
]
53
},
54
Advertisement
Answer
Clarification : resources
array contains all the resourceType that we are comparing using if/else
clause ? As Array.map()
will return the same number of elements as input array contains otherwise it will return with undefined.
Suggestion : Instead of multiple if/else-if
clause, we can use multiple if
statements for a better performance.
Demo :
JavaScript
1
52
52
1
// Response coming from API.
2
const resources = [{
3
resourceType: 'brand',
4
url: 'brandUrl'
5
}, {
6
resourceType: 'product',
7
url: 'productUrl'
8
}, {
9
resourceType: 'category',
10
url: 'categoryUrl'
11
}, {
12
resourceType: 'document',
13
url: 'documentUrl'
14
}];
15
16
// Array of required ResourceTypes.
17
const requiredResourceTypes = ['brand', 'product', 'document'];
18
19
// Logic to filter and get the URL's object of the required resourceTypes.
20
const urlModule = resources.filter(({resourceType}) => requiredResourceTypes.includes(resourceType)).map((resource) => {
21
const { resourceType } = resource
22
if (resourceType === 'brand') {
23
return {
24
url: `/${resource.url}`,
25
changefreq: 'weekly',
26
priority: 0.9,
27
}
28
}
29
if (resourceType === 'product') {
30
return {
31
url: `/${resource.url}`,
32
changefreq: 'monthly',
33
priority: 0.8,
34
}
35
}
36
if (resourceType === 'category') {
37
return {
38
url: `/${resource.url}`,
39
changefreq: 'weekly',
40
priority: 0.7,
41
}
42
}
43
if (resourceType === 'document') {
44
return {
45
url: `/${resource.url}`,
46
changefreq: 'weekly',
47
priority: 0.6,
48
}
49
}
50
});
51
52
console.log(urlModule);
Performance test result screenshot :