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.

 

 

TLDR – QUICK SLIDES

[web_stories_embed url=”https://code-boxx.com/web-stories/convert-object-to-string-in-javascript/” title=”Convert Object To String In Javascript” poster=”https://code-boxx.com/wp-content/uploads/2023/02/STORY-JS-R4.webp” width=”360″ height=”600″ align=”center”]

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

DOWNLOAD & NOTES

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

 

QUICK NOTES

If you spot a bug, feel free to comment below. I try to answer short 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.

 

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.

 

 

JAVASCRIPT 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 obj = {
  name : "Joa Doe",
  email : "joa@doe.com",
  address : "123 Doe Street"
};
 
// (B) JSON ENCODE TO STRING
// {"name":"Joa Doe","email":"joa@doe.com","address":"123 Doe Street"}
var str = JSON.stringify(obj);
console.log(str);

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 obj = {
  name : "Job Doe",
  email : "job@doe.com",
  address : "123 Doe Street"
};
 
// (B) MANUAL FOR LOOP
// name:Job Doe, email:job@doe.com, address:123 Doe Street
var str = "";
for (let [k,v] of Object.entries(obj)) {
  str += `${k}:${v}, `;
}
str = str.substring(0, str.length -2);
console.log(str);

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) OBJECT WITH CUSTOM STRINGIFY FUNCTION
var obj = {
  name : "Joe Doe",
  email : "joe@doe.com",
  address : "123 Doe Street",
  stringify : function () {
    let str = "";
    str += `name: ${this.name}, `;
    str += `email: ${this.email}, `;
    str += `address: ${this.address}`;
    return str;
  }
};

// (B) CALL THE STRINGIFY() FUNCTION
// name: Joe Doe, email: joe@doe.com, address: 123 Doe Street
var str = obj.stringify();
console.log(str);

// (C) THE CONVENIENCE - CHANGING PROPERTIES
// name: Joi Doe, email: joi@doe,com, address: 123 Doe Street
obj.name = "Joi Doe";
obj.email = "joi@doe,com";
str = obj.stringify();
console.log(str);

Speaking of functions in objects – Yes, for 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 obj = {
  name: "Jon Doe",
  email: "jon@doe.com",
  address: "123 Doe Street"
};
 
// (B) JAVASCRIPT HAS A NATIVE "TO STRING" FUNCTION
// BUT IT DOES NOTHING ON OBJECTS
console.log(obj.toString); // function - native code
console.log(obj.toString()); // object

// (C) AS SUGGESTED BY SOME OTHER TUTORIALS
// WE CAN OVERRIDE THE PROTOTYPE TO STRING FUNCTION
// name: Jon Doe, email: jon@doe.com, address: 123 Doe Street
Object.prototype.toString = function () {
  let str = "";
  str += `name: ${this.name}, `;
  str += `email: ${this.email}, `;
  str += `address: ${this.address}`;
  return str;
};
console.log(obj.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 {
  // (A1) SET PROPERTIES
  constructor (name, email, address) {
    this.name = name;
    this.email = email;
    this.address = address;
  }
 
  // (A2) STRINGIFY FUNCTION
  stringify () {
    let str = "";
    str += `name: ${this.name}, `;
    str += `email: ${this.email}, `;
    str += `address: ${this.address}`;
    return str;
  }
}

// (B) CREATE OBJECT
var obj = new person(
  "Joy Doe",
  "joy@doe.com",
  "123 Doe Street"
);

// (C) CALL STRINGIFY() FUNCTION
// name: Joy Doe, email: joy@doe.com, address: 123 Doe Street
var str = obj.stringify();
console.log(str);

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.

 

 

EXTRA 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

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Javascript Object To String (Click to enlarge)

 

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 *