Giả sử sau đây là mảng JSON của chúng tôi -
var details = [
{
"customerDetails": [
{
"customerName": "John Smith",
"customerCountryName": "US"
}
]
},
{
"customerDetails": [
{
"customerName": "David Miller",
"customerCountryName": "AUS"
}
]
},
{
"customerDetails": [
{
"customerName": "Bob Taylor",
"customerCountryName": "UK"
}
]
}
] Để chỉ nhận các giá trị CustomerName, hãy sử dụng khái niệm map () -
Ví dụ
var details = [
{
"customerDetails": [
{
"customerName": "John Smith",
"customerCountryName": "US"
}
]
},
{
"customerDetails": [
{
"customerName": "David Miller",
"customerCountryName": "AUS"
}
]
},
{
"customerDetails": [
{
"customerName": "Bob Taylor",
"customerCountryName": "UK"
}
]
}
]
var allCustomerName = details.map(obj=>
obj.customerDetails[0].customerName);
console.log(allCustomerName); Để chạy chương trình trên, bạn cần sử dụng lệnh sau -
node fileName.js.
Ở đây tên tệp của tôi là demo206.js.
Đầu ra
PS C:\Users\Amit\javascript-code> node demo206.js [ 'John Smith', 'David Miller', 'Bob Taylor' ]