Để chuyển đổi giá trị kiểu chuỗi thành kiểu mảng, hãy sử dụng phương thức parse (). Sau đây là mã -
Ví dụ
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); Để chạy chương trình trên, bạn cần sử dụng lệnh sau -
node fileName.js.
Đầu ra
Ở đây, tên tệp của tôi là demo123.js. Điều này sẽ tạo ra kết quả sau -
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' }
]