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"
}
]
}
}
}
CodePudding user response:
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);
CodePudding user response:
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) ;