3 Ways To Convert String To Object In Javascript

Welcome to a short tutorial on how to convert a string into an object in Javascript. Well, for a quick answer –

The only native Javascript function to convert a string into an object is JSON.parse(). For example, var parsed = JSON.parse('{"foo":"bar"}'). To convert strings of other formats, it has to be done manually.

 

That covers the basics, but let us walk through a few more examples in this guide – Read on!

ⓘ 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.

 

QUICK SLIDE

 

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.

 

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.

 

 

OBJECT TO STRING

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

 

1) JSON PARSE

1-json.js
// (A) JSON ENCODED STRING
var thestring = '{"Name":"Jon Doe","Email":"jon@doe.com","Address":"123 Doe Street"}';

// (B) PARSE JSON
var theobj = JSON.parse(thestring);

/* Name: "Jon Doe",
 * Email: "jon@doe.com",
 * Address: "123 Doe Street"
 */
console.log(theobj);

For you beginners who have not heard of it – JSON stands for Javascript Object Notation. Simply put, turning an array or object in a string. The JSON.stringify(OBJECT) will turn an object into a JSON encoded string, then we use the JSON.parse(STRING) function to turn it back into an object.

 

2) MANUAL FOR LOOP

2-for.js
(A) CSV STRING
var thestring = "Name,Joe Doe,Email,joe@doe.com,Address,234 Doe Street";

// (B) MANUAL PROCESS AND LOOP
var temp = thestring.split(","),
    theobj = {};
for (let i=0; i<temp.length; i+=2) {
  theobj[temp[i]] = temp[(i+1)];
}

/* Name: "Joe Doe",
 * Email: "joe@doe.com",
 * Address: "234 Doe Street"
 */
console.log(theobj);

So what if the “original string” is not in JSON format? Well, it is kind of bad in this situation. As the only way is to manually process the string. In the above example, we have a string in comma-separated values (CSV) format.

Assuming that the CSV string is kept in a KEY, VALUE, KEY, VALUE, ... format. We first split the values up using split(","), then piece them back into an object one by one.

 

 

3) “IMPORT” FUNCTION

3-function.js
// (A) THE EXISTING OBJECT
var theobj = {
  // (A1) OBJECT PROPERTIES
  Name: null,
  Email: null,
  Address: null,

  // (A2) IMPORT FROM CSV STRING
  inCSV : function (str) {
    let tempA = str.split(","),
        tempB = {};
    for (let i=0; i<tempA.length; i+=2) {
      tempB[tempA[i]] = tempA[(i+1)];
    }
    this.Name = tempB.Name;
    this.Email = tempB.Email;
    this.Address = tempB.Address;
  },

  // (A3) IMPORT FROM JSON STRING
  inJSON : function (str) {
    let temp = JSON.parse(str);
    this.Name = temp.Name;
    this.Email = temp.Email;
    this.Address = temp.Address;
  }
};

// (B) PROCESS "IMPORT"
// (B1) CSV
var dataA = "Name,Job Doe,Email,job@doe.com,Address,345 Doe Street";
theobj.inCSV(dataA);
 
/* Name: "Job Doe",
 * Email: "job@doe.com",
 * Address: "345 Doe Street"
 */
console.log(theobj);

// (B2) JSON
var dataB = '{"Name":"Joy Doe","Email":"joy@doe.com","Address":"456 Doe Street"}';
theobj.inJSON(dataB);
 
/* Name: "Joy Doe",
 * Email: "joy@doe.com",
 * Address: "456 Doe Street"
 */
console.log(theobj);

Yes, we can put functions into an object. So if you have an existing object, and just want to “import” some values from a string – Simply create your own version of the “import from string” functions. The above example walks through 2 flavors of importing, from a JSON string, and from a CSV string.

 

 

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.

 

LINKS & REFERENCES

 

INFOGRAPHIC CHEAT SHEET

Convert String To Object In JS (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.