1

What I'm trying to do is conditionally rendering of one element in my object, i.e. if the chosenHour key (inside hoursInfo array) equals to 19:30 then I'd like to have this whole element not to be rendered, so I would have just two elements instead of three.

The problem is that IFE returns null if the condition is not met so I still have object of three elements with second element of null. All is done in React so I thought it is good idea to use IFE in order to use if statement without else part.

Here's my code:

bookingObjToSend = {
    name, email, phone, kidsNo, adultsNo, fullDate, year, month, day, chosenRoom,
    hoursInfo: [
        { chosenHour: 
            chosenHour ==='9:30' ? '9:15' :
            chosenHour ==='12:00' ? '12:15' :
            chosenHour ==='14:30' ? '13:45' :
            chosenHour ==='17:00' ? '16:45' :
            chosenHour ==='19:30' ? '19:45' : null ,
         renderedByBirthday: true, isBirthday: false },
        (() => {
            if(chosenHour !== '19:30'){ return { chosenHour:                         
                chosenHour ==='9:30' ? '10:45' :
                chosenHour ==='12:00' ? '13:45' :
                chosenHour ==='14:30' ? '15:15' :
                chosenHour ==='17:00' ? '18:15' :
                null ,
             renderedByBirthday: true, isBirthday: false}}
        })(),
        { chosenHour, isBirthday: true}
    ]
}
0

1 Answer 1

1

You could use filter to filter out all falsy elements from the array to get rid of the potential null values.

bookingObjToSend = {
    name, email, phone, kidsNo, adultsNo, fullDate, year, month, day, chosenRoom,
    hoursInfo: [
        { chosenHour: 
            chosenHour ==='9:30' ? '9:15' :
            chosenHour ==='12:00' ? '12:15' :
            chosenHour ==='14:30' ? '13:45' :
            chosenHour ==='17:00' ? '16:45' :
            chosenHour ==='19:30' ? '19:45' : null ,
         renderedByBirthday: true, isBirthday: false },
        (() => {
            if(chosenHour !== '19:30'){ return { chosenHour:                         
                chosenHour ==='9:30' ? '10:45' :
                chosenHour ==='12:00' ? '13:45' :
                chosenHour ==='14:30' ? '15:15' :
                chosenHour ==='17:00' ? '18:15' :
                null ,
             renderedByBirthday: true, isBirthday: false}}
        })(),
        { chosenHour, isBirthday: true}
    ].filter(Boolean)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.