ในการแปลงค่าประเภทสตริงเป็นประเภทอาร์เรย์ ให้ใช้เมธอด parse() ต่อไปนี้เป็นรหัส -
ตัวอย่าง
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); ในการรันโปรแกรมข้างต้น คุณต้องใช้คำสั่งต่อไปนี้ -
node fileName.js.
ผลลัพธ์
ที่นี่ ชื่อไฟล์ของฉันคือ demo123.js สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -
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' }
]