I would like to generate cases in a switch statement from an array. Here is how the array is generated:
pointObjects = [];
for (var i = 0; i < 2; i++) {
// Generate cases.
var url;
var pointObject =
{
case: 'Placeholder',
url: 'google.com'
}
pointObjects.push(pointObject);
}
Thus, pointObjects[0] returns:
{
case: 'Placeholder'
url: 'google.com
}
I’d like to render these each within a switch statement, so it will act the same as the code below:
click: function(event) {
var seriesName = this.name;
var url;
// Attaches the query link to the respective slice.
switch (seriesName) {
case 'Placeholder':
url = 'google.com';
break;
case 'Placeholder':
url = 'google.com';
break;
default:
url = '#';
}
// Opens the query in a new tab
if (url !== '#') {
window.open(url, '_blank');
}
}
I tried the following code but it says that pointObjects is an unexpected identifier:
switch (seriesName) {
pointObjects.forEach(obj => {
case obj.case:
url = obj.url;
break;
});
default:
url = '#';
}
2
Answers
The only things that you can put inside of a
switch
statement arecase
clauses anddefault
clauses. Anything else, such as trying to callpointObjects.forEach
, is illegal syntax. As a result, you cannot dynamically change the number of switch statements. Instead, you will need to write your code using other techniques.For example, a for loop:
Or using the
.find
method on arrays:If changing
pointObjects
is an option, you could also turn it into an object and do a lookup by key:You don’t have to use
switch/case
. Neither do you have to use an array. How about the following?