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

更新於: 01-Sep-2020

4K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告