8 Ways to Convert JavaScript Object to String

From utilizing the JSON.stringify() method for JSON representation to invoking the toString() method or the String() constructor, the post will guide you through each approach.

Jun 20, 2023 | Read time 10 minutes

🔔 Table of contents

Introduction

When developing with Javascript - either in the front end or backend, you will come across a scenario where you need to convert a Javascript object to string.

Now a use case could be that you need to save the object in the database or you just want a clear view of all the object properties.

I had to do this with a recent app where we want to have a “preview” of the Javascript object.

I came across 8 ways that we can do this, and list it out in this blog.

JSON.stringify()

The JSON.stringify() method takes an object as an argument and returns a string that represents the object in JSON format. It recursively converts all the enumerable properties of the object and their values into a string.

Here’s an example usage of JSON.stringify():

const obj = {
  name: 'John',
  age: 30,
  city: 'New York'
};

const jsonString = JSON.stringify(obj);
console.log(jsonString);

Output:

{"name":"John","age":30,"city":"New York"}

In the example above, the obj object is converted into a JSON string using JSON.stringify(). The resulting JSON string contains all the key-value pairs of the object. Note that the property names are enclosed in double quotes, which is a requirement in JSON.

The JSON.stringify() method also provides additional parameters to control the string conversion process. Here are a few commonly used parameters:

  • replacer (optional): A function or an array that specifies how values should be transformed or filtered before stringification. It can be used to selectively include or exclude specific properties from the resulting JSON string.
  • space (optional): A string or a number that specifies the indentation level for pretty-printing the JSON string. It can be used to make the resulting string more human-readable.
  • toJSON method (optional): If an object being stringified has a toJSON method, this method will be called and its return value will be stringified.

You can refer to the MDN web documentation for JSON.stringify() for more information and detailed examples: JSON.stringify() - MDN Web Docs

Disadvantages of using JSON.stringify()

  • Circular References - If the object being stringified contains circular references (where an object references itself in a loop), JSON.stringify() will throw an error.

  • Function Properties - you will lose your object functions when JSON.stringify is applied. This also means that when you convert back from the string, the function will not work.

  • Date Serialization - date objects can be tricky since they will be converted to strings using the Date.prototype.toISOString() method. Now when you convert the date will be converted back to a string, not a Date object.

  • Limited Data Types - JSON.stringify() can handle most common data types such as strings, numbers, arrays, and objects. However, it cannot handle certain JavaScript-specific data types such as Map, Set, and undefined. So when your object contains these types, they will be omitted.

  • Property Order - The order of properties in the resulting JSON string is not guaranteed to be the same as the order of properties in the original object.

  • Performance - JSON.stringify() can be computationally expensive, especially for large and complex objects. Serializing deeply nested objects or objects with a large number of properties can impact performance.

toString()

One option is to use the toString() method. Use this if you have simple objects.

If the object has a toString() method implemented, you can use it to convert the object to a string.

const obj = { key: 'value', toString: () => 'Custom String' };
const str = obj.toString();
console.log(str); // 'Custom String'

String class

We can use the String() constructor to get a string representation of a Object.

You can use the String() constructor to explicitly convert an object to a string.

const obj = { key: 'value' };
const str = String(obj);
console.log(str); // '[object Object]'

Now this does not help you see the properties of the object so not quite helpful in most cases. I have used this option when doing unit testing.

String concatenation

String concatenation: By concatenating an object with an empty string (''), JavaScript will automatically convert it to a string.

JavaScript automatically converts non-string values to strings when they are concatenated with strings. This behavior is known as implicit conversion or type coercion.

For example, when you use the + operator to concatenate a string with a number, boolean, or other non-string value, JavaScript converts the non-string value to its string representation and then performs the concatenation.

const str1 = 'Hello';
const num = 42;
const bool = true;

const result1 = str1 + num; // 'Hello42'
const result2 = str1 + bool; // 'Hellotrue'

Using the call method

function objToString (obj) {
    var str = '';
    for (var p in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, p)) {
            str += p + '::' + obj[p] + '\n';
        }
    }
    return str;
}

Modern approach

function objToString (obj) {
    let str = '';
    for (const [p, val] of Object.entries(obj)) {
        str += `${p}::${val}\n`;
    }
    return str;
}

or:

function objToString (obj) {
    return Object.entries(obj).reduce((str, [p, val]) => {
        return `${str}${p}::${val}\n`;
    }, '');
}

The Object.entries() method in JavaScript returns an array containing an object’s enumerable property key-value pairs. Each key-value pair is represented as a two-element array within the resulting array.

The syntax for using Object.entries() is as follows:

Object.entries(obj)

Here’s an explanation of the components:

obj: The object whose enumerable property key-value pairs you want to retrieve. The Object.entries() method provides an easy way to iterate over an object’s properties using array iteration methods like forEach(), map(), or for…of loops.

Here’s an example to illustrate how Object.entries() works:

const person = {
  name: 'John Doe',
  age: 30,
  city: 'New York'
};

const entries = Object.entries(person);

console.log(entries);

Output:

[  ["name", "John Doe"],
  ["age", 30],
  ["city", "New York"]
]

In the example above, we have an object person with three properties: name, age, and city. By using Object.entries(person), we obtain an array where each property is represented as a two-element array with the key-value pair.

Once you have the array of key-value pairs, you can perform various operations on it. For instance, you can use array methods like forEach() to iterate over the entries or map() to transform the entries into a different format.

It’s important to note that the Object.entries() method only retrieves enumerable properties. Non-enumerable properties, such as properties created using Object.defineProperty() with enumerable: false, will not be included in the resulting array.

The Object.entries() method is especially useful when you need to work with an object’s properties in a key-value pair format. It provides a convenient way to extract and manipulate object data, making it easier to perform tasks such as serialization, filtering, or transforming the properties.

Use NPM package stringify-object

Yeoman recently released a stringify object library.

Now this can be useful for when you want to get the string representation of an object in a formatted way.

It also handles circular references and lets you specify quote type.

https://www.npmjs.com/package/stringify-object

npm install stringify-object
import stringifyObject from 'stringify-object';

const object = {
	foo: 'bar',
	'arr': [1, 2, 3],
	nested: {
		hello: "world"
	}
};

const pretty = stringifyObject(object, {
	indent: '  ',
	singleQuotes: false
});

console.log(pretty);
/*
{
	foo: "bar",
	arr: [
		1,
		2,
		3
	],
	nested: {
		hello: "world"
	}
}
*/

Using template literals

let obj = {
  name: "John",
  age: 22,
  isDev: true,
};
let toStr = "";
for (let key in obj) {
  if (obj.hasOwnProperty(key)) {
    toStr += `${key} ${obj[key]}` + ", ";
  }
}
console.log(toStr);
console.log(typeof toStr);

Console.log()

Now in the case that you just want to debug, then console log function is adequate.

console.log('Item: %o', o);

It will print out the object properties and allow you to inspect further.

Browser compatibility

  • The JSON.stringify() method is pretty safe to use and compatible amongst all browsers - Chrome, Edge, Firefox, Opera,etc. In the unfortunate scenario where you still have to use older browsers, we careful since IE 6 and 7 is not supported.

Summary

Generally, when we need to convert a Javascript object over to a string, I would go for the JSON.stringify() method. This is a pretty straight forward method and will work with most scenarios.

The downside is that you have to think about issues such as

  • Circular References,
  • Date Serialization,
  • Limited Data Types,
  • Property Order and
  • performance.

If you end up encountering these issues, then I would suggest to use a NPM solution such as https://www.npmjs.com/package/stringify-object by the team behind Yeoman which will deal with these issues.

👋 About the Author

G'day! I am Huy a software engineer based in Australia. I have been creating design-centered software for the last 10 years both professionally and as a passion.

My aim to share what I have learnt with you! (and to help me remember 😅)

Follow along on Twitter , GitHub and YouTube