Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

JavaScript: Lấy tất cả giá trị 'name' trong mảng JSON?


Giả sử mảng JSON như sau:

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

Để lấy chỉ customerName, dùng 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: node fileName.js. File demo206.js.

Kết quả

PS C:\Users\Amit\javascript-code> node demo206.js [ 'John Smith', 'David Miller', 'Bob Taylor' ]