How to convert objects to string in JavaScript

JavaScript program to convert an object to string:

JavaScript objects consists of key-value pairs. You need to convert an object to string in many cases. For example, if you want to save the string representation of the object to localstorage, or in your own database.

In this post, I will show you a couple of ways to convert a JavaScript object to string.

Method 1: By using JSON.stringify():

The JSON.stringify() method converts a JavaScript object to a JSON string. This is a common method used to convert a JavaScript object to string.

The syntax of the JSON.stringify() method is as below:

JSON.stringify(v, replacer, space)

Here,

  • v is the JSON object that we need to convert to a string.
  • replacer is optional. It is a function that can change the stringification process.
  • space is another optional value. This argument can be used to control the space in the final result string. It can be a number or string.

It returns the final JSON string, i.e. the string representation of the JSON object. Or it might return undefined.

Let me show you how it works with an example:

let student = {
  name: "Alex",
  age: 20,
  address: "A/B",
};

const strStudent = JSON.stringify(student);

console.log(strStudent);

It will print:

{"name":"Alex","age":20,"address":"A/B"}

It works with nested objects as well. For example:

let student = {
  name: "Alex",
  age: 20,
  address: {
    house: "A/B",
    state: "Blah",
  },
};

const strStudent = JSON.stringify(student);

console.log(strStudent);

It will print:

{"name":"Alex","age":20,"address":{"house":"A/B","state":"Blah"}}

JavaScript object to string

Method 2: How to print an object on console:

The console.log() function can be used to print an object on console. If you concatenate the object with a string and use console.log, it will print [object Object].

For example,

let student = {
  name: "Alex",
  age: 20,
  address: {
    house: "A/B",
    state: "Blah",
  },
};

console.log('Student '+ student);

It will print:

Student [object Object]

If you want to print the JSON objects as strings, you can either use %o or you can pass it as the second parameter to console.log.

console.log('Student:', student);
console.log('Student: %o', student);

Both of these will print:

Student: { name: 'Alex', age: 20, address: { house: 'A/B', state: 'Blah' } }

If you want to convert an object to string and save it to a database, you can use JSON.stringify() and if you want to print the data for debugging purpost, you can pass it as the second parameter to console.log or you can use %o.

You might also like: