1

I have a json file with data that gets passed into a component. Some objects have all 3 variables and some have some data missing. We want to display something like:

-Alice, Seattle WA

but if Seattle and WA aren't present we want to display just

-Alice

And vice versa. And hide the hyphen if nothing is present. What's the cleanest way to do this?

 <div>
     - {item.name}, {item.city} {item.state}
 </div>
Max T
  • 1,205
  • 3
  • 18
  • 33

3 Answers3

0

Perhaps you could resolve this in the following way:

 <div>
     - {item.name} { (item.city && item.state) && `, ${item.city} {item.state}` }
 </div>
Dacre Denny
  • 28,232
  • 5
  • 37
  • 57
0

You can do something like this

<div>
   - {item.name + (item.city ? ', ' + item.city : '') + (item.state ? ' ' + item.state : '')}
<div>

or you could simplify further

<div>
   - {item.name} { (item.city && item.state) && `, ${item.city} {item.state}` }
</div>
Smokey Dawson
  • 7,596
  • 15
  • 68
  • 133
0
const address = `${item.name}, ${item.city} ${item.state}`
  ? `-${item.name}, ${item.city} ${item.state}`
  : null;

Display like this:

{address}

Anil Kumar
  • 2,073
  • 2
  • 16
  • 20