This blog will illustrate the methods for converting the string into an object using JavaScript.
How to Convert String to Object in JavaScript?
For converting a string to an object in JavaScript, use the following approaches:
Method 1: Convert String to Object Using “JSON.parse()” Method in JavaScript
Utilize the “JSON.parse()” method for converting the string to an object. It parses the string value into an object. For this, the mentioned method takes a JSON string as an argument, which needs to be parsed and then returns the JavaScript object created from the JSON string.
Syntax
Use the given syntax for JSON.parse() method for parsing a string to convert an object:
Here, “JSONstring” is the string that will be parsed into the JSON.
Example
Create a variable “myString” that stores a JSON string:
Now, verify the type of string “myString” using the “typeof” operator:
Call the JSON.parse() method and pass the string as a parameter and store the resultant object in variable “myObject”:
Print the converted object on the console utilizing the “console.log()” method:
The output is evident that the string has been successfully converted into the object:
Method 2: Convert String to Object Using the “split()” Method
You can also use the “split()” method for converting string to an object. It divides/breaks a string in an ordered list of substrings to search for the specified pattern and gives the substrings in an array form.
Syntax
Follow the given syntax for the split() method:
Here, the “pattern” corresponds to the character or expression on which the string will split.
Example
Create a comma-separated string:
Call the split() method by passing the pattern or character (,) to split the string and store the substrings in variable “myArray”:
Create an empty object named “myObject”:
Iterate the array (splitted substrings) using the “for” loop and map the elements in the empty created object:
myObject[myArray[i]] = myArray[(i+1)];
}
Finally, print the resultant object on the console:
Output
That was all about converting string to object in JavaScript.
Conclusion
For converting a string to an object, use the “JSON.parse()” method or the “split()” method. In real-time projects, the “JSON.parse()” method is the most commonly and efficiently used method. It is important to note that it can throw an error if the string passed to it is not valid JSON. In this write-up, we demonstrated JavaScript’s methods for converting the string into an object.