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: 2020-09-10T07:06:03+05:30

397 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements