I have an object with the following data.
I want to build a string from it but I need it to be in a specific order.
const info = {
first: 'John',
last: 'Doe',
middle: 'Henry',
suffex: 'Sr',
}
result = John Henry Doe Jr
Here is what I have but I’d like to get rid of the if/else
const name= `${info.first}${
info.middle ? ' ' + info.middle : ''
} ${info.last}${info.suffix ? ' ' + info.suffix : ''}`
4
Answers
You can use the
?.
operatorFilter an array with conditional chaining
Alternatively use optional chaining, nullish coalescing operator and remove extra space using a RegExp
Alternatively if the objects are in correct order
You map to an array and filter on empty
OR Operator in JavaScript
You can use OR
||
inJavaScript
.I wrote a little script and I used the OR operator.
Working Code:
I believe that this is the cleanest solution for your issue. Feel free to comment if you have any questions.
I like keeping the code very clear with intention and what it is trying to do, as below:
Another way utilizing generators: