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!

 

 

TLDR – QUICK SLIDES

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

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

 

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
/* 
 Name: "Jon Doe",
 Email: "jon@doe.com",
 Address: "123 Doe Street"
*/
var theobj = JSON.parse(thestring);
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 into 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
/*
 Name: "Joe Doe",
 Email: "joe@doe.com",
 Address: "234 Doe Street"
*/
var temp = thestring.split(","), theobj = {};
for (let i=0; i<temp.length; i+=2) {
  theobj[temp[i]] = temp[(i+1)];
}
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 : str => {
    let tempA = str.split(","), tempB = {};
    for (let i=0; i<tempA.length; i+=2) {
      tempB[tempA[i]] = tempA[(i+1)];
    }
    theobj.Name = tempB.Name;
    theobj.Email = tempB.Email;
    theobj.Address = tempB.Address;
  },

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

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

// (B2) JSON
/*
 Name: "Joy Doe",
 Email: "joy@doe.com",
 Address: "456 Doe Street"
*/
var dataB = '{"Name":"Joy Doe","Email":"joy@doe.com","Address":"456 Doe Street"}';
theobj.inJSON(dataB);
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” function. The above example walks through 2 flavors of importing, from a JSON string, and from a CSV string.

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

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.

 

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. Required fields are marked *