adam_gataev
2 years agoNew Contributor II
IF Statement in Expressions Library file
Hi,
I have an expressions library file which creates a JSON object like this:
...
.map((elem, idx, arr) =>
{
"fieldA": elem.fieldA,
"fieldB": [
{
"fieldC1": elem.fieldC1,
"fieldC2": elem.fieldC2
},
{
"fieldD1": elem.fieldD1,
"fieldD2": elem.fieldD2
},
{
"fieldE1": elem.fieldE1,
"fieldE2": elem.fieldE2
}
]
}
)
...
"fieldB" is an array of objects. The first object ("fieldC") will always be present, but for the second ("fieldD") and third ("fieldE") objects that is not always the case.
How can I create a condition that will remove the whole {...} based on whether elem.fieldD1 or elem.fieldE1 exist?
I think there is only the ternary operator ( a ? b : c ), but I am not sure how to insert the ternary operator here.
Is something like this correct:
...
{
"fieldC1": elem.fieldC1,
"fieldC2": elem.fieldC2
}, /* what about this "," (comma)? If D1 does not exist, then the comma should not be there.*/
(elem.fieldD1) ? "{ "fieldD1": elem.fieldD1, "fieldD2": elem.fieldD2 }," : ""
(elem.fieldE1) ? "{ "fieldE1": elem.fieldE1, "fieldE2": elem.fieldE2 }" : ""
...
Lastly, you only have these 3 objects inside the array and nothing more.
The order is always kept. If fieldD does not exist, fieldE doesn't either.
Does someone know how I can achieve this result?
Best regards,
Adam
adam_gataev - you were very close - try this
.map((elem, idx, arr) => { "fieldA": elem.fieldA, "fieldB": [ { "fieldC1": elem.fieldC1, "fieldC2": elem.fieldC2 } ] .concat( elem.get('fieldD1') > '' ? [ { "fieldD1": elem.fieldD1, "fieldD2": elem.fieldD2 } ] : [] ) .concat( elem.get('fieldE1') > '' ? [ { "fieldE1": elem.fieldE1, "fieldE2": elem.fieldE2 } ] : [] ) } )
Hope this helps!