Để chuyển đổi giá trị kiểu chuỗi sang kiểu mảng, hãy sử dụng phương thức JSON.parse(). Dưới đây là mã:
Ví dụ
var customerDetails = '[ { "name": "John", "countryName": "US" }, { "name": "David", "countryName": "AUS" }, { "name": "Bob", "countryName": "UK" } ]';
console.log("Giá trị thực tế=" + customerDetails);
var convertStringToArray = JSON.parse(customerDetails);
console.log("Sau khi chuyển chuỗi sang mảng đối tượng=");
console.log(convertStringToArray);
Để chạy chương trình trên, bạn cần sử dụng lệnh sau:
node fileName.js
Kết quả
Tên tệp của tôi là demo123.js. Chương trình sẽ cho ra kết quả sau:
PS C:\Users\Amit\JavaScript-code> node demo123.js
Giá trị thực tế=[{"name": "John", "countryName": "US"}, {"name": "David", "countryName": "AUS"}, {"name": "Bob", "countryName": "UK"}]
Sau khi chuyển chuỗi sang mảng đối tượng=[
{ name: 'John', countryName: 'US' },
{ name: 'David', countryName: 'AUS' },
{ name: 'Bob', countryName: 'UK' }
]