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

JavascriptWeb DevelopmentObject Oriented Programming

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' }
]
raja
Published on 10-Sep-2020 10:35:21
Advertisements