How to get comma separated values from an array of objects in JavaScript?

Background

Let's say we want to get the following output...

Global Administrator, Technical Administrator, Global User

... from the below JavaScript object ...

var myObjArray = [
  {roleCode: "GlobalAdmin", roleDescription: "Global Administrator"},
  {roleCode: "TechnicalAdmin", roleDescription: "Technical Administrator"},
  {roleCode: "GlobalUser", roleDescription: "Global User"}
]

Simply put, we need to get a comma delimited string from an array of objects by using JavaScript. More in detail, we just want to get the result from a specific field for each element in the array, this case as from roleDescription one.

Solution

A simple way of achieving it is by using the map() and join() JavaScript functions:

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

The join()  method creates and returns a new string by concatenating all of the elements in an array.

var myObjArray = [
  {roleCode: "GlobalAdmin", roleDescription: "Global Administrator"},
  {roleCode: "TechnicalAdmin", roleDescription: "Technical Administrator"},
  {roleCode: "GlobalUser", roleDescription: "Global User"}
]
// Returns a new array with role descriptions
.map(function(element){
    return element.roleDescription;
})
// Concatenates elements from previous role description array with a comma and a blank
.join(", ");

console.log(myObjArray);

The map() method returns a new array holding elements with just "role descriptions" and then, the join() methods concatenates all the elements from the previous array by using the ", ", namely, a comma and a blank.

So, it is very easy, do not use weird loops for getting the same!!

 

 

 

Add comment