JavaScript How to get all 'name' values in a JSON array?

JavascriptWeb DevelopmentObject Oriented Programming

Let’s say the following is our JSON array −

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

To get only the CustomerName values, use the concept of map() −

Example

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);

To run the above program, you need to use the following command −

node fileName.js.

Here my file name is demo206.js.

Output

PS C:\Users\Amit\javascript-code> node demo206.js
[ 'John Smith', 'David Miller', 'Bob Taylor' ]
raja
Published on 01-Sep-2020 11:07:27
Advertisements