How to Convert Array into string, comma,hyphen in javascript/Angular

During application development, a list of records data retrieved from REST API is in the form of an Array of records in javascript.

let assume   Permissions REST API returns the list of  permissions for user in an application for example following are array of permissions returned from API,

let array=["READ","WRITE", "DELETE","UPLOAD"];

This posts talks about how do we convert the array into string in javascript/Angular?

javascript convert Array to string

There are multiple ways we can output to a string

Using array map with join method

  • Inbuilt map with String join method
  • array map method is used in the following example.
  • map iterates the each element applies callback
  • append each element using join method of the string
  • join method accepts a string which appends to it.

below the line of code convert to string with comma

console.log(stringwithcomma) //READ,WRITE,DELETE,UPLOAD

converted string contains hypen separated for below line of code

the same way we can use for spaces converted to string separated with spaces

let>element).join(" ")
console.log(stringwithspace)//READ WRITE DELETE UPLOAD

This approach works with any type of array and any type of delimiter.

Using toString method

every object in javascript has toString() method

Array also this method which prints the string representation of an array separated with commas.

This only works with primitive types not with an array of objects.


Convert object array to String in angular

data comes from REST API and wants to display in the string. these data need to display in client-side using angular codebase

This post does not talks about retrieving the data from API.

Assume that the following data is available in the typescript component.

This will be an example where we need to display the user’s information in the data table each row can have user information, one of the columns need to display the roles names separated with a comma.

Converted to string using map iterator and finally join the string with a separate hyphen.

import { Component } from "@angular/core";

  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
export class AppComponent {
  name = "Angular";
  roles = [
    { id: "1", name: "superadmin" },
    { id: "2", name: "admin" },
    { id: "3", name: "user" }
  roleString: String = null;
  constructor() {
    this.roleString = =>"-");

in component html template, displaying the string using template expression.

Similar Posts