JavaScript如何获取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' ]
广告