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,365
  • 4
  • 23
  • 38

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
  • 29,664
  • 5
  • 45
  • 65
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
  • 8,827
  • 19
  • 77
  • 152
0
const address = `${item.name}, ${item.city} ${item.state}`
  ? `-${item.name}, ${item.city} ${item.state}`
  : null;

Display like this:

{address}

Anil Kumar
  • 2,223
  • 2
  • 17
  • 22