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.
4
Answers
You can use the slice() method to remove the last character from the resulting string:
You can use the following regular expression:
To find a semicolon in the end of the string, then replace it with an empty string.
The regular expression has the following meaning:
;
matches the literal semicolon(s|\n)*
matches one or more white spaces, orn
literals$
matches the end of the stringYou could update the code to join the array with
;n
and if you want to keep the extra line in between then;nn
Don’t add the semi-colon in the
map
call, but use it as separator in the finaljoin
call.Not an issue, but:
Boolean
as filter callback function.''
, you can return.checked
when it is falsy, which allows you to return one expression withoutif..else
.