Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Get only specific values in an array of objects in JavaScript?
When working with arrays of objects in JavaScript, you often need to extract specific values based on certain criteria. This can be accomplished using several array methods like filter(), map(), and find().
Let's say we have the following array of student objects:
var details = [{
studentName: "John",
studentMarks: 92
},
{
studentName: "David",
studentMarks: 89
},
{
studentName: "Mike",
studentMarks: 98
}];
Using filter() to Get Objects Meeting Criteria
The filter() method creates a new array with all objects that pass a test condition:
var details = [{
studentName: "John",
studentMarks: 92
},
{
studentName: "David",
studentMarks: 89
},
{
studentName: "Mike",
studentMarks: 98
}];
var specificValuesFromArray = details.filter(obj => obj.studentMarks === 92 || obj.studentMarks === 98);
console.log(specificValuesFromArray);
[
{ studentName: 'John', studentMarks: 92 },
{ studentName: 'Mike', studentMarks: 98 }
]
Using map() to Extract Specific Properties
If you only need specific property values, use map() to create a new array:
var details = [{
studentName: "John",
studentMarks: 92
},
{
studentName: "David",
studentMarks: 89
},
{
studentName: "Mike",
studentMarks: 98
}];
// Get only student names
var studentNames = details.map(obj => obj.studentName);
console.log(studentNames);
// Get only marks above 90
var highMarks = details.filter(obj => obj.studentMarks > 90).map(obj => obj.studentMarks);
console.log(highMarks);
[ 'John', 'David', 'Mike' ] [ 92, 98 ]
Using find() to Get Single Object
Use find() when you need only the first object that matches your criteria:
var details = [{
studentName: "John",
studentMarks: 92
},
{
studentName: "David",
studentMarks: 89
},
{
studentName: "Mike",
studentMarks: 98
}];
var topScorer = details.find(obj => obj.studentMarks > 95);
console.log(topScorer);
{ studentName: 'Mike', studentMarks: 98 }
Comparison of Methods
| Method | Returns | Use Case |
|---|---|---|
filter() |
Array of matching objects | Get all objects meeting criteria |
map() |
Array of extracted values | Transform each object to get specific properties |
find() |
First matching object | Get single object meeting criteria |
Conclusion
Use filter() to get multiple objects matching criteria, map() to extract specific properties, and find() for the first matching object. These methods provide flexible ways to work with arrays of objects in JavaScript.
