How to Convert a JavaScript Object to a String of Values?

To convert a JavaScript object to a string of values, you can do the following:

  1. Convert the object to an array of values using Object.values();
  2. Convert the resulting array to a string using Array.prototype.join().

For example, to create a comma separated string from an object's property values, you can do the following:

const obj = { foo: 'bar', baz: 'qux', quux: 'corge' };
// 1: convert object to array of values
const arr = Object.values(obj);
// 2: convert array to comma separated string
const str = arr.join(',');

console.log(str); // "bar,qux,corge"

Consider another example, where you can make each item in the comma separate string wrapped in single quotes:

const obj = { foo: 'bar', baz: 'qux', quux: 'corge' };
// 1: convert object to array of values
const arr = Object.values(obj);
// 2: convert array items to comma separated strings, wrapped in single quotes
const str = `'${arr.join("','")}'`;

console.log(str); // "'bar','qux','corge'"

You can do the same with double quotes (instead of single quotes) in the following way:

const obj = { foo: 'bar', baz: 'qux', quux: 'corge' };
// 1: convert object to array of values
const arr = Object.values(obj);
// 2: convert array items to comma separated strings, wrapped in double quotes
const str = `"${arr.join('","')}"`;

console.log(str); // '"bar","qux","corge"'

Knowing this will help you quickly transform object data into a format suitable for various applications, such as constructing SQL queries, generating CSV files, or formatting data for specific API requests.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.