简体   繁体   中英

How do i use nested ternary operator in my code? Javascript

Trying to use nested ternary operator in my code

Code:

let ele_Partition = records[0].data.meeting ?  
  records[0].data.meeting.partition : records[0].data.partition;

Need to add another data for the same condition.

records[0].data.meeting.meetingPartition

How to implement it without nested if-else?

let ele_Partition = records[0].data.meeting ? 
  records[0].data.meeting.partition : records[0].data.meeting.meetingPartition ? 
    records[0].data.meeting.meetingPartition : records[0].data.partition;

If records[0].data.meeting , set the variable to records[0].data.meeting.partition .

Else if records[0].data.meeting.meetingPartition , set the variable to records[0].data.meeting.meetingPartition

Else set the variable to records[0].data.partition .

You should avoid nested ternary operators as they make your code incredibly complicated to read.

I would take a single ternary with a default value

let ele_Partition = records[0].data.meeting
        ? records[0].data.meeting.partition
        : records[0].data.meeting.meetingPartition || records[0].data.partition;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM