5 Ways To Convert Object To String In Javascript

Welcome to a quick tutorial on how to convert an object to string in Javascript. Need to convert an object into a string, then transfer or store it?

There is only one native Javascript function to turn an object into a string – the JSON.stringify() function. So if you are looking for alternative ways to convert an object into a string, the only option is to create a custom “to string” function.

Yep, that is what we will be covering in this guide – Read on for more examples!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

REAL QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Object To String Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

OBJECT TO STRING

All right, let us now get into the various ways we can create functions (or processes) to turn an object into a string.

 

1) JSON ENCODE

1-json.html
// (A) THE OBJECT
var theobj = {
  name : "John Doe",
  email : "john@doe.com",
  address : "123 Doe Street"
};
 
// (B) JSON ENCODE TO STRING
var thestring = JSON.stringify(theobj);
// {"name":"John Doe","email":"john@doe.com","address":"123 Doe Street"}
console.log(thestring);

This is the only native Javascript function that turns an object to a string, and what is JSON? Javascript Object Notation. For beginners who have not heard of it, it is simply a way to represent arrays and objects in string format… Use JSON.stringify(OBJECT) to turn an array or object into a JSON encoded string, and JSON.parse(STRING) to turn it back.

 

 

2) MANUAL LOOP & CONVERT

2-for.html
// (A) THE OBJECT
var theobj = {
  name : "John Doe",
  email : "john@doe.com",
  address : "123 Doe Street"
};
 
// (B) MANUAL FOR LOOP
var thestring = "";
for (let i in theobj) {
  thestring += i + ":" + theobj[i] + ", ";
}
thestring = thestring.substring(0, thestring.length -2);
 
// name:John Doe, email:john@doe.com, address:123 Doe Street
console.log(thestring);

This one should be straightforward and “newbie-friendly”. We are simply running through the object using a for-in loop to create a string. But take note – This will not dig into nested objects.

 

3) CUSTOM STRINGIFY FUNCTION

3-stringify.html
// (A) CREATE OBJECT WITH CUSTOM STRINGIFY FUNCTION
var theobj = {
  name : "John Doe",
  email : "john@doe.com",
  address : "123 Doe Street",
  stringify : function(){
    let thestring = "";
    thestring += "name :" + this.name + ", ";
    thestring += "email :" + this.email + ", ";
    thestring += "address :" + this.address;
    return thestring
  }
};

// (B) CALL THE STRINGIFY() FUNCTION
var thestring = theobj.stringify();
// name :John Doe, email :john@doe.com, address :123 Doe Street
console.log(thestring);

// (C) THE CONVENIENCE - CHANGING PROPERTIES
theobj.name = "Jane Doe";
theobj.email = "jane@doe,com";
thestring = theobj.stringify();
// name :Jane Doe, email :jane@doe.com, address :123 Doe Street
console.log(thestring);

Speaking of functions in objects – Yes, for the beginners who do not know, we can put functions into objects. So in this case, we create our own custom stringify() function and use it to output whatever properties we want as a string.

 

 

4) OVERRIDE TO-STRING PROTOTYPE FUNCTION

4-prototype.html
// (A) THE OBJECT
var theobj = {
  name: "John Doe",
  email: "john@doe.com",
  address: "123 Doe Street"
};
 
// (B) JAVASCRIPT HAS A NATIVE "TO STRING" FUNCTION
// BUT IT DOES NOTHING ON OBJECTS...
console.log(theobj.toString);
// [object Object]
console.log(theobj.toString());

// (C) AS SUGGESTED BY SOME OTHER TUTORIALS...
// WE CAN OVERRIDE THE PROTOTYPE TO STRING FUNCTION
Object.prototype.toString = function() {
  let thestring = "Name: " + this.name;
  thestring += "Email: " + this.email;
  thestring += "Address: " + this.address;
  return thestring;
};
 
// Name: John DoeEmail: john@doe.comAddress: 123 Doe Street
console.log(theobj.toString());

This is one that I found somewhere on the Internet. Yep, Javascript actually has a native toString() function, but it does nothing for objects. The whole idea here is to override the native toString() function with your own… While it works, I will not recommend messing with native prototype functions. Just create a separate function of your own.

 

5) JAVASCRIPT CLASS

5-class.html
// (A) PERSON CLASS
class person {
  constructor(name, email, address) {
    this.name = name;
    this.email = email;
    this.address = address;
  }
 
  stringify() {
    let thestring = "Name: " + this.name;
    thestring += "Email: " + this.email;
    thestring += "Address: " + this.address;
    return thestring;
  }
}

// (B) CREATE OBJECT
var theobj = new person(
  "John Doe",
  "john@doe.com",
  "123 Doe Street"
);

// (C) CALL STRINGIFY() FUNCTION
var thestring = theobj.stringify();
console.log(thestring);

If overriding the native toString() function is not recommended, then what is the “correct way” to do it? Simply follow the above function-in-object, or create a new class. Yes, Javascript supports the “traditional object-oriented class” and create a “new CLASS” mechanism since ECMA 2015.

You guys who have used other OOP languages should be right at home with this one. Just add a stringify() function in the class and all corresponding objects will inherit it.

 

 

USEFUL BITS & LINKS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

WHICH ONE TO USE?

Well, it depends on what you are trying to do.

  • If you intend to turn the object into a string for the purpose of transferring data (for example, submitting a form to the server) – JSON makes more sense.
  • But if you intend to display the object data to the user – Creating a custom “format object data into a nice string” function makes more sense.

 

SUMMARY

Function Description Reference Link
JSON.stringify(OBJECT) Turns an array or object into a JSON encoded string. Click Here
Object.prototype.toString() Native to string function. Click Here

 

INFOGRAPHIC CHEAT SHEET

Javascript Object To String (Click to enlarge)

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

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