Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

JavaScript วิธีดึงค่า 'name' ทั้งหมดในอาร์เรย์ JSON?


สมมติอาร์เรย์ JSON ของเราเป็นดังนี้

var details = [ { "customerDetails": [ { "customerName": "John Smith", "customerCountryName": "US" } ] }, { "customerDetails": [ { "customerName": "David Miller", "customerCountryName": "AUS" } ] }, { "customerDetails": [ { "customerName": "Bob Taylor", "customerCountryName": "UK" } ] } ]

เพื่อดึงเฉพาะค่า CustomerName ใช้คอนเซปต์ของ 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' ]