Convert Object Values To Comma Separated String JS

In this article, we will cover how to convert object values to comma separated string in JavaScript.

To achieve this, we need to create an array from the object values using the `Object.values()` method and then use the `join()` method on the generated array passing in `,` as an argument to specify the join character. It will then return a string with all the values joined on the comma symbol.

Convert Object Values To Comma Separated String

First, let’s start by creating our object and initializing it with values –

const obj = {

  key1: "value1”,

  key2: "value2”,

  key3: "value3”,

  key4: "value4”

};

Then, we will create an array of the object values using the `Object.values()` method –

const values = Object.values(obj);

Now, we need to use the `join()` method on the `values` array passing in `,` comma symbol as an argument to join all the values inside of the array into a string separated by a comma. Then we will print the result on the console.

console.log(values.join(",”));
object values converted to comma separated string

As we can see, we got all the values as one string and values are separated with a `,` comma.

We have to note one thing – the `join()` method returns an empty string if it is called on an empty string, empty array, null, or undefined values. To avoid falling into this issue, we can make sure that the array we pass to the `join()` method contains valid elements.

Let’s modify our object and convert `key2` to an empty string and `key4` to null –

const obj = {

  key1: "value1”,

  key2: "”,

  key3: "value3”,

  key4: null

};

If we check our console when joining the array of values, we can see we got two blank spots in the string, once between `value1` and `value3` and another after `value3`.

blank spots in string

We will use the `filter()` method on the array of values passing in `Boolean` as an argument to check for invalid values. The `Boolean` object evaluates to `false` if it comes across false values such as: `””`, `undefined`, `null`, `0`, `false` and evaluates to `true` otherwise.

We will then print the output on the console to check the values we got.

console.log(values.filter(Boolean).join(",”));
no blank spots while joining the string

As we can see, we got values of properties `key2` and `key4` eliminated from our string since they contained an empty string`””`  and `null`.

Leave a Reply