สมมติว่าต่อไปนี้คืออาร์เรย์ JSON ของเรา –
var details = [
{
"customerDetails": [
{
"customerName": "John Smith",
"customerCountryName": "US"
}
]
},
{
"customerDetails": [
{
"customerName": "David Miller",
"customerCountryName": "AUS"
}
]
},
{
"customerDetails": [
{
"customerName": "Bob Taylor",
"customerCountryName": "UK"
}
]
}
] หากต้องการรับเฉพาะค่าชื่อลูกค้า ให้ใช้แนวคิดของ map() -
ตัวอย่าง
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); ในการรันโปรแกรมข้างต้น คุณต้องใช้คำสั่งต่อไปนี้ -
node fileName.js.
ชื่อไฟล์ของฉันคือ demo206.js
ผลลัพธ์
PS C:\Users\Amit\javascript-code> node demo206.js [ 'John Smith', 'David Miller', 'Bob Taylor' ]