简体   繁体   中英

How to use ternary operator for multiple conditions?

trying to add multiple conditions using ternary operator, values are coming false every time what is the issue with below code? based on isActive flag value should set

index.js

   const _res: any = {}

_res.memberPreferences.channels.EM = (details.memberPreferences.channels[0].channelType === "EM" && details.memberPreferences.channels[0].isActive === "true") ? true : false;
_res.memberPreferences.channels.SMS = (details.memberPreferences.channels[0].channelType === "SMS" && details.memberPreferences.channels[0].isActive === "true") ? true : false

data

here is how the data is returned

{
    "details": {
        "memberPreferences": {
            "channels": [{
                    "channelType": "EM",
                    "isActive": "true"
                },
                {
                    "channelType": "SMS",
                    "isActive": "false"
                }
            ]
        }
    }
}

You need no ternary, just the result of the comparison.

 const details = { memberPreferences: { channels: [{ channelType: "EM", isActive: "true" }, { channelType: "SMS", isActive: "false" }] } }, _res = { memberPreferences: { channels: {} } }, target = _res.memberPreferences.channels; details.memberPreferences.channels.forEach(({ channelType, isActive }) => { target[channelType] = isActive === "true"; }); console.log(_res);

You don't actually need ternary operator here. The condition itself returns either true or false . Also, it's good to create separate variables for details.memberPreferences.channels[0] and channel_zero.isActive == "true" condition. And here there is no need to use === over == . So the index.js should look like this:

const _res: any = {};
const channel_zero: any = details.memberPreferences.channels[0];
const is_active: boolean = channel_zero.isActive == "true";

_res.memberPreferences.channels.EM = (channel_zero.channelType == "EM" && is_active);
_res.memberPreferences.channels.SMS = (channel_zero.channelType == "SMS" && is_active) ;

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