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 −

Example

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=");
console.log(convertStringToArray);

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

node fileName.js.

Output

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' }
]

Updated on: 10-Sep-2020

288 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements