Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript How to get all 'name' values in a JSON array?
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' ]
Advertisements