Trying to convert Switch statement to if else statement - Help please

I am trying to redo some of the examples in Request, to familiarize with request and also JS in general, and was stuck with below code. The original code is written in ‘Switch,case’ conditional statement, I am trying to use ‘If else’ statement.

//Original:
const formatJson = (resJson) => {
resJson = JSON.stringify(resJson);
let counter = 0;
return resJson.split(’’)
.map(char => {
switch (char) {
case ‘,’:
return ,\n${' '.repeat(counter * 2)};
case ‘{’:
counter += 1;
return {\n${' '.repeat(counter * 2)};
case ‘}’:
counter -= 1;
return \n${' '.repeat(counter * 2)}};
default:
return char;
}
})
.join(’’);
};

//My version:
const formatJson = (resJson) => {
resJson = JSON.stringify(resJson);
let counter = 0;
return resJson.split(’’).map(char => {
if (char == ‘,’) {
return ,\n${' '.repeat(counter * 2)};
} else if (char == ‘{’) {
return counter +=
{\n${' '.repeat(counter * 2)};
} else if (char == ‘}’) {
return counter -=
\n${' '.repeat(counter * 2)}};
} else {
return char;
}
}).join(’’)
};

The problem, I narrowed down, it’s the ‘counter’. In switch statement, after comparing case with the switch, if truthy, we can add the counter, but I can’t seems to do it in if else statement.

Please help, thanks in advanced.

Hey, well you are not really counting anything, you are saying counter += but with no value to add.
Also you are returning the counter instead of the string.

Comparing this with the switch statement this should be:

} else if (char == '{') {
    counter += 1;
    return bla bla
} 

Hey thank you so much, I must be tired and not looking at the most obvious thing. Really appreciate your help.:slightly_smiling_face:

1 Like

Sure, anytime that’s what we are here for :wink: . Happy coding!

This topic was automatically closed 18 hours after the last reply. New replies are no longer allowed.