Search code examples
javascriptarraysreactjslodash

Don't pass value to component if string equals "" empty


I'm passing values to my component but some have a value of "". This creates a visual container which is empty on my view. I need the value not to pass at all if it equals "".

<AddIntel initialValues={{
    pastIntelNotes: [
    profile.intelNotes,
    profile.intelNotes2,
    profile.intelNotes3,
    profile.intelNotes4
]
}} />

I've tried a conditional

<AddIntel initialValues={{
    pastIntelNotes: [
    profile.intelNotes,
    profile.intelNotes2 != "" ? profile.intelNotes2 : null,
    profile.intelNotes3,
    profile.intelNotes4
]
}} />

null is being past to the component which still maps it as a length

initialValues:
   pastIntelNotes: Array(4)
     0: "Notes"
     1: null
     2: "Notes2"
     3: "Notes3"
length: 4

I am looking for this:

initialValues:
  pastIntelNotes: Array(3)
     0: "Notes"
     1: "Notes2"
     2: "Notes3"
length: 3

Solution

  • Try this:

    const pastIntelNotes = [profile.intelNotes, profile.intelNotes2, profile.intelNotes3, profile.intelNotes4];
    
    <AddIntel initialValues={{
       pastIntelNotes: pastIntelNotes.filter(note => note !== ""),
    }} />