Search code examples
javascriptarraysjsontypescript

Remove Comma From Each Line


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?


Solution

  • .join can be used at the end of arrays to avoid the commas :

    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": [] } ];
    
    const formatted = data.map(c => c.included.map(d => 
      'Included\n\nFor Level ' + d.levelColumnName + 
      '\n\nTabs' + d.tabs.map(e => '\n- ' + e.tabName).join('') + 
      '\n\nPermissions' + d.levels.map(e => '\n- ' + e.permName).join('') )).join('\n');
    
    console.log( formatted );