Flowers on tree

Converting an object to a string in JavaScript

As you know, an object is a special structure that can hold some values in computer memory. Also, there may be some methods that allow you to manipulate that data.

But what if you'd want to convert that object to a string value and send it over the network? Or maybe you want to save it in a database?

That is possible in the JavaScript language. Please read the following sections and see how to convert an object to a string.

Using the JSON.stringify() method

That's probably the most common method that can be used in a web project. JavaScript language provides the JSON.stringify() static method that may help you to make a string from some object.

It's very simple to use. You have to provide at least a single parameter, which is the object to convert. Then, that method will return a single value that can be used in your code.

See the following sample that shows how to print the given object to a screen.

const product = {
    title: 'Computer mice'
};

const productSerialized = JSON.stringify(product);

console.log(productSerialized);

Now, let's run the given code and see the console output.

developer@developer-pc:~/samples/javascript$ node index.js
{"title":"Computer mice"}

The JSON.stringify() method also has some additional parameters that can be specified in your code. In our example, we will use the last one, which allows us to configure the indentation. Please see the following code sample. We have the number 4 there. This means that each level of indentation will contain four additional space characters.

const product = {
    title: 'Computer mice'
};

const productSerialized = JSON.stringify(product, null, 4);

console.log(productSerialized);

To see how the code works, please run it in the console with help of the NodeJS tool.

developer@developer-pc:~/samples/javascript$ node index.js
{
    "title": "Computer mice"
}

Directly converting specific value to a string

As you probably know, JavaScript has the String object. However, if it is called as a function, it converts a given value to a string. And that functionality can be used to convert the specific object to a string.

But there is an important note. Such a method has some limitations. The whole content of the given object may not be saved into a string.

The following sample shows how each type of data can be converted to a string in JavaScript.

const product = {
    title: 'Computer mice'
};

console.log(String(product));
console.log(String({}));
console.log(String({name: "keyboard"}));
console.log(String([1, 2, 3, 4, 5]));
console.log(String(new Date("2023-01-01")));
console.log(String(Boolean(0)));
console.log(String(Boolean(1)));
console.log(String("777"));
console.log(String(777));

It's time to run the given code sample. See the console output below. As you see, the objects are not fully converted. There is just a notice that the given value contains some object.

developer@developer-pc:~/samples/javascript$ node index.js
[object Object]
[object Object]
[object Object]
1,2,3,4,5
Sun Jan 01 2023 01:00:00 GMT+0100 (Central European Standard Time)
false
true
777
777

Using the Object.prototype.toString() method

Each object in JavaScript may have the toString() method. It allows you to return the string value that contains the state of the specific object. And you can customize that string according to your needs.

The following code shows how it can be done. There, we create our own toString() method for the "Product" object. It will return the name of the product.

function Product(title) {
    this.title = title;
}

const productObject = new Product('Computer mice');

Product.prototype.toString = function productToString() {
    return `${this.title}`;
};

console.log(productObject.toString());

Please run the given code sample. You should see the product title in your terminal.

developer@developer-pc:~/samples/javascript$ node index.js
Computer mice

Using a custom method to convert object to a string

If none of the above methods work for you, then you can create a custom code that will convert an object into a string. JavaScript language is flexible. Your code may format the string according to your specific needs.

To enumerate the properties of an object, we may use the for..in operator. Then, inside of the loop, we may save keys and values into some array. Finally, when the loop has ended, the array items may be merged into a single string with help of the join() method.

Below is an example that shows how it has to be done.

const product = {
    title: 'Computer mice',
    price: 29
};

function serializeObject(object) {
    const keyPairs = [];

    for (const key in object) {
        if (Object.prototype.hasOwnProperty.call(object, key)) {
            keyPairs.push(key + '=' + object[key]);
        }
    }

    return keyPairs.join('|');
}

const productSerialized = serializeObject(product);

console.log(productSerialized);

If you run the given code, you should see the state of the object in your console.

developer@developer-pc:~/samples/javascript$ node index.js
title=Computer mice|price=29

Using the Object.entries() method to iterate over the properties

The Object class has the entries() method. It returns an array of properties of the given object. Each item of that array is also an array that contains key and value.

After we obtain that list, we can use the for…of loop to iterate over the properties. The same as it shown in the previous method, we save key and value pairs into the "keyPairs" array. That array will be converted to a string with help of the join() method.

const product = {
    title: 'Computer mice',
    price: 29
};

function serializeObject(object) {
    const keyPairs = [];

    for (const [key, value] of Object.entries(object)) {
        keyPairs.push(key + '=' + value);
    }

    return keyPairs.join('|');
}

const productSerialized = serializeObject(product);

console.log(productSerialized);

Following is the output of the given code sample.

developer@developer-pc:~/samples/javascript$ node index.js
title=Computer mice|price=29

Using the Object.entries() and Array.map() methods to make a compact code

To make a compact code, we can replace the for…of loop by the Array.map() method. It will iterate over the properties and will convert key and value pairs into a string value. After that, we can combine all items into another single string value with help of the join() method.

All those operations can be made in a single line of code, as it's shown below.

const product = {
    title: 'Computer mice',
    price: 29
};

function serializeObject(object) {
    return Object.entries(object).map(entry => entry.join('=')).join('|');
}

const productSerialized = serializeObject(product);

console.log(productSerialized);

Let's try to run the given code. It should print the state of the object into your terminal.

developer@developer-pc:~/samples/javascript$ node index.js
title=Computer mice|price=29

Using the Array.forEach() method and getting value directly from the object

JavaScript also has the Object.keys() method. It allows you to get only keys of a specific object. If you'd like to use that method in your code, you can also create key and value pairs. But in that case, you have to manually obtain value from the object with help of the […] operator. See the following sample that shows how it has to be done.

const product = {
    title: 'Computer mice',
    price: 29
};

function serializeObject(object) {
    const keyPairs = [];

    Object.keys(object).forEach(key => keyPairs.push(key + "=" + object[key]));

    return keyPairs.join('|');
}

const productSerialized = serializeObject(product);

console.log(productSerialized);

Please run the given code sample. The console output should be as shown below.

developer@developer-pc:~/samples/javascript$ node index.js
title=Computer mice|price=29

Recursive method of converting object to a string

Some of the above custom methods may only process simple objects. But how would you convert an object that has another nested object?

In such a case, you may write a code that can recursively convert each nested property to a string. You only have to check the type of the value. If that's an object, then we apply our serialization method. If that is another type of data, then we call the regular toString() method. Following is our example that shows how it can be implemented.

const product = {
    title: 'Computer mice',
    price: 29,
    details: {
        in_stock: true,
        size: 20,
        color: 'black'
    }
};

function serializeObject(object) {
    if (object === null) {
        return String(object);
    }

    switch (typeof object)
    {
        case "object": {
            return '{' + Object.keys(object).map( key => {
                return key + '=' + serializeObject(object[key]);
            }).join('|') + '}';
        }

        default: {
            return object.toString();
        }
    }
}

const productSerialized = serializeObject(product);

console.log(productSerialized);

The console output of this method is shown below.

developer@developer-pc:~/samples/javascript$ node index.js
{title=Computer mice|price=29|details={in_stock=true|size=20|color=black}}

Using the console.log() method

This method will not directly convert an object to a string. If you just need to see contents of the object for the testing purposes, then this option may be suitable.

As you know, JavaScript has the console.log() method. You can use it to simply print the state of some object to the browser console.

const product = {
    title: 'Computer mice',
    price: 29
};

console.log(product);

If you run the given code, you should see the string representation of the object in your terminal.

developer@developer-pc:~/samples/javascript$ node index.js
{ title: 'Computer mice', price: 29 }

But please pay attention that this method has some limitations. If an object is too deep, the JavaScript engine may print only a limited version of your object.

Using the console.dir() method

You may also use the console.dir() method to print the state of the object to the console.

It's similar to the previous method, you have to pass a single parameter to make it working. The difference is that this method outputs dynamic values. Each property can be expanded. In other words, you may review each level of your object in the console.

const product = {
    title: 'Computer mice',
    price: 29
};

console.dir(product);

To see exactly how the above code works, please run it in the console with help of the NodeJS tool.

developer@developer-pc:~/samples/javascript$ node index.js
{ title: 'Computer mice', price: 29 }

Using the lodash map() method

That's an alternative method to make a string from some object. The lodash library has the map() method. It also can be used to iterate over the properties of some object. That will allow you to obtain key and value pairs.

Then, the final array can be converted to a string with help of the join() method. Example is shown below.

import _ from 'lodash';

const product = {
    title: 'Computer mice',
    price: 29
};

function serializeObject(object) {
    return _.map(object, (value, key) => key + '=' + value).join('|');
}

const productSerialized = serializeObject(product);

console.log(productSerialized);

If you run the given code, the console output should be like the following.

developer@developer-pc:~/samples/javascript$ node index.js
title=Computer mice|price=29

Recursive method of converting object to a string

Previous method converts only simple objects. But if you'd like to convert objects that have nested levels, then you need to improve the given code. In our sample, we use the recursion to process each nested element. However, you may modify and adapt that code to your needs.

import _ from 'lodash';

const product = {
    title: 'Computer mice',
    price: 29,
    details: {
        in_stock: true,
        size: 20,
        color: 'black'
    }
};

function serializeObject(object) {
    if (object === null) {
        return String(object);
    }

    switch (typeof object)
    {
        case "object": {
            return '{' + _.map(object, (value, key) => {
                return key + '=' + serializeObject(value)
            }).join('|') + '}';
        }

        default: {
            return object.toString();
        }
    }
}

const productSerialized = serializeObject(product);

console.log(productSerialized);

Now, let's verify that the given code works. You can run it with help of the NodeJS tool. The console output is given below. As you may see, inner fields are printed to the terminal.

developer@developer-pc:~/samples/javascript$ node index.js
{title=Computer mice|price=29|details={in_stock=true|size=20|color=black}}

Using the util.inspect() method in NodeJS

If you are making a NodeJS application, then you can use the util.inspect() method. It allows you to directly convert an object to a string. The method is very simple. You can get the contents of an object in just one line of a code. Please see below how to use it.

import util from 'util';

const product = {
    title: 'Computer mice',
    price: 29
};

console.log(util.inspect(product));

To test the given code, you may run it in the console as shown below.

developer@developer-pc:~/samples/javascript$ node index.js
{ title: 'Computer mice', price: 29 }

Conclusion

If you need to convert an object to a string, that's not an issue. JavaScript has various methods that may help you. In most cases, the built-in API should fulfill your needs.

However, if you have some non-standard case, then you may write your own code that will iterate over each property and convert it to a string value.

Also, you have the ability to log the object to the browser console. It can be done with the help of the console.log() or console.dir() methods.

Related Articles

Navigation html code

How to add JavaScript code to HTML

Comma separated numbers

Rounding number to at least 2 decimal places in JavaScript or TypeScript

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *