In my opinion you are refactoring the wrong thing. Obviously you are looking at your code and see that it is a bit of a mess with two places where the code seem to be repeated but not quite:
if (name === FieldNames.SecurityQuestion1) {
resetField(FieldNames.FirstAnswer, '');
resetField(FieldNames.ConfirmFirstAnswer, '');
} else if (name === FieldNames.SecurityQuestion2) {
resetField(FieldNames.SecondAnswer, '');
resetField(FieldNames.ConfirmSecondAnswer, '');
}
Realise that the ternary operator is just an if in expression context instead of a statement. Converting it will result in exactly the same mess with less readable syntax.
If you REALLY want to know the correct ternary expression for the code you have it looks exactly the same:
selectedItem?.value ?
name === FieldNames.SecurityQuestion1 ?
resetField(FieldNames.FirstAnswer, '')
:
resetField(FieldNames.ConfirmFirstAnswer, '')
:
name === FieldNames.SecurityQuestion2 ?
resetField(FieldNames.SecondAnswer, '')
:
resetField(FieldNames.ConfirmSecondAnswer, '');
The above is the correct way to abuse the ternary operator and get the same result. However, notice that it is still the same code and the same mess. And if you put the : in the wrong place it would be a bug and produce the wrong result!! The braces {} used by the if statement makes understanding and debugging the code much easier because it clarifies when a condition starts and when it ends.
The way to refactor this is to realize that Question1 and Question2 have common data. So structure it that way:
const FieldNames = {
Security: {
First: {
Question: '...',
Answer: '...',
Confirm: '...'
},
Second: {
Question: '...',
Answer: '...',
Confirm: '...'
}
}
}
Now you can refactor it like this:
const handleChange = ({ selectedItem }) => {
if (selectedItem?.value) {
for (let f of ['First', 'Second']) {
if (name === FieldNames.Security[f].Question) {
resetField(FieldNames.Security[f].Answer, '');
resetField(FieldNames.Security[f].Confirm, '');
}
}
}
};
This reduces duplicated code and makes your code DRY (and hence more compact) without reducing readability.