const arr = [
{
"id": "753311",
"role": "System Of Record (SOR)",
"license": "Target",
"DC": "Client · L2 (Inactive), Account · L1",
"managedGeography": "North America · L2, International · L2",
"managedSegment": "Institutional Clients Group [L3], Discontinued Ops [L2]",
"checked": true,
"checkBoxPatched": true
},
{
"id": "752872",
"role": "Authorized Redistributor (AR)",
"license": "Interim",
"DC": "Holding · L1, Document · L1, Compliance · L1",
"managedGeography": "Unspecified",
"managedSegment": "Unspecified",
"checked": true,
"checkBoxPatched": true
},
{
"id": "752583",
"role": "Authorized Redistributor (AR)",
"license": "Target",
"DC": "Agreement · L1, Asset · L1, Activity · L1, Account · L1",
"managedGeography": "Unspecified",
"managedSegment": "Unspecified"
}
]
let adsList = arr.map(selectedObj => {
if (selectedObj.checked) {
return selectedObj.role + ", " + selectedObj.license + ", " + selectedObj.DC + ", " + selectedObj.managedGeography + ", " + selectedObj.managedSegment + ";\n"
} else {
return '';
}
}).filter((str) => str.length !== 0).join('\n');
console.log(adsList)
Hi there I’ve an array and I’m basically returning the string if object contains checked property and separating them with semicolon, but need to remove for the last one.
I’m not sure how do I remove the last semicolon after unspecified from the output in this case, any leads would be quite helpful.
>Solution :
Don’t add the semi-colon in the map call, but use it as separator in the final join call.
Not an issue, but:
- you can use
Booleanas filter callback function. - Instead of returning
'', you can return.checkedwhen it is falsy, which allows you to return one expression withoutif..else. - Maybe use a template string for concatenating the properties with commas.
const arr = [{"id": "753311","role": "System Of Record (SOR)","license": "Target","DC": "Client · L2 (Inactive), Account · L1","managedGeography": "North America · L2, International · L2","managedSegment": "Institutional Clients Group [L3], Discontinued Ops [L2]","checked": true,"checkBoxPatched": true},{"id": "752872","role": "Authorized Redistributor (AR)","license": "Interim","DC": "Holding · L1, Document · L1, Compliance · L1","managedGeography": "Unspecified","managedSegment": "Unspecified","checked": true,"checkBoxPatched": true},{"id": "752583","role": "Authorized Redistributor (AR)","license": "Target","DC": "Agreement · L1, Asset · L1, Activity · L1, Account · L1","managedGeography": "Unspecified", "managedSegment": "Unspecified"}];
let adsList = arr.map(obj =>
obj.checked && `${obj.role}, ${obj.license}, ${obj.DC}, ${obj.managedGeography}, ${obj.managedSegment}`
).filter(Boolean).join(';\n\n');
console.log(adsList)