Borislav Hadzhiev
Thu Nov 04 2021·2 min read
Photo by Vitaly Sacred
To convert an object's values to a comma-separated string, use the
Object.values()
method to get an array of the object's values and concatenate
them into a comma-separated string using the join()
method, e.g.
Object.values(obj).join(',')
.
const obj = { country: 'Chile', city: 'Santiago', code: 1234, }; const str = Object.values(obj).join(','); console.log(str); // 👉️ "Chile,Santiago,1234"
We used the Object.values method to get an array of the object's values.
const obj = { country: 'Chile', city: 'Santiago', code: 1234, }; // 👇️ ['Chile', 'Santiago', 1234] console.log(Object.values(obj));
The last step is to use the Array.join method to join the array into a string based on a provided separator.
We need a comma-separated string so we passed a comma to the join
method.
console.log(['a', 'b', 'c'].join(',')); // 👉️ "a,b,c" console.log(['a', 'b', 'c'].join(', ')); // 👉️ "a, b, c"
If you use this approach on an empty object, you would get an empty string back.
console.log(Object.values({}).join(',')); // 👉️ ""
This is because the Object.values
method returns an empty array when provided
an empty object.
console.log(Object.values({})); // 👉️ []
If called on an array with length 0
, the join
method returns an empty
string.
console.log([].join(',')); // 👉️ ""
If the object contains null
, undefined
or empty array []
values, the
join
method converts them to an empty string.
const obj = { country: undefined, city: null, code: 1234, }; // 👇️ [undefined, null, 1234] console.log(Object.values(obj)); const str = Object.values(obj).join(','); console.log(str); // 👉️ ",,1234"
Because the values of the country
and city
properties are undefined
and
null
, they got converted to an empty string, but we still get the
comma-separator between the values.
If you need to handle this scenario, you can use the filter()
method to filter
for truthy values before joining them into a string.
const obj = { country: undefined, city: null, code: 1234, key: 'test', }; // 👇️ "1234,test" console.log(Object.values(obj).filter(Boolean).join(','));
We used the Boolean
object to convert each element in the array to a boolean.
If the conversion of the value to boolean returns true
, it gets added to the
array the filter
method returns.
The Boolean
object converts all falsy values to false
and all truthy values
to true
.
The falsy values in JavaScript are: false
, null
, undefined
, 0
, ""
(empty string), NaN
(not a number).
All other values get converted to true
, meaning if the string contains at
least 1 character the Boolean
object will convert it to true
and it will be
added to the array that the filter
method returns.
This prevents us from joining empty string elements and having one separator next to the other.