JavaScript 如何获取 JSON 数组中的所有"名称"值?

javascriptweb developmentobject oriented programming更新于 2025/10/29 22:04:17

假设以下是我们的 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' ]

相关文章


有用资源