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' ]