How to convert string type value to array type in JavaScript?

To convert string type value to array type, use the parse() method. Following is the code −


var customerDetails='[
   {"name": "John", "countryName": "US"},
   {"name": "David", "countryName": "AUS"},
   {"name": "Bob", "countryName": "UK"}
console.log("The actual value="+customerDetails);
var convertStringToArray=JSON.parse(customerDetails);
console.log("After converting string to array objects=");

To run the above program, you need to use the following command −

node fileName.js.


Here, my file name is demo123.js. This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo123.js
The actual value=[{"name": "John", "countryName": "US"}, {"name": "David", "countryName":
"AUS"}, {"name": "Bob", "countryName": "UK"}]
After converting string to array objects=[
   { name: 'John', countryName: 'US' },
   { name: 'David', countryName: 'AUS' },
   { name: 'Bob', countryName: 'UK' }