I was able to format the json
data as I expected and here’s the code snippet that I tried so far:
const data = [
{
"id": 654298,
"included": [
{
"id": 654298,
"levelColumn": "DIM4_COL5",
"levelColumnName": "Region",
"isIncluded": true,
"tabs": [
{
"tabId": 640111,
"tabName": "Growth"
},
{
"tabId": 640031,
"tabName": "Direct Sales"
},
{
"tabId": 640021,
"tabName": "Operator Review"
}
],
"levels": [
{
"permValue": "WEST FS",
"permName": "WEST FS"
}
]
}
],
"excluded": []
}
];
var formatted = "Included n" +
data.map(c => c.included.map(d => `nFor Level `
+ d.levelColumnName
+ `nTabs ${d.tabs.map(e => `n- `
+ e.tabName.toString().split(",").join("n n"))}n` +
`nPermissions ${d.levels.map(e => `n- `
+ e.permName.toString().split(",").join("n n"))}n` ));
console.log(formatted);
There could be place for improvement, but for now this is what I got.
The Output I get now:
Included
For Level Region
Tabs
- Growth,
- Direct Sales,
- Operator Review
Permissions
- WEST FS
Pretty much what I was expecting. Somehow I am not able to remove the comma from each line of the Tabs grouping. Seems like if Permissions grouping had multiple values too, it would also have trailing commas.
I was hoping split(",").join("n n")
would eliminate that, but that didn’t work out. Any way to remove the trailing commas?
2
Answers
You are (implicitly) calling
String()
on an array here:Your real data does not have a comma in it, so
split
does nothing. The result ofmap
is an array with three items:['n- Growth', 'n- Direct Sales', 'n- Operator Review']
.`${array}`
is equivalent toString(array)
, which callsString()
on all array items and finally joins the result with a comma, resulting in'n- Growth,n- Direct Sales,n- Operator Review'
.Instead, you want to join the array’s items with line breaks and then interpolate the resulting string:
It’s also a bit odd that you keep mixing template literals with string concatenation. Note that template literals can span multiple lines and include literal line breaks. Functions can help a lot as well to keep your code readable and extensible:
.join
can be used at the end of arrays to avoid the commas :