How to filter nested objects in JavaScript?
Last Updated :
24 Jun, 2024
Improve
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Below are the approaches used to filter nested objects in JavaScript:
Table of Content
Method 1: Using filter() method
Example: This approach uses the filter() method to filter the nested object in JavaScript.
<!DOCTYPE html>
<html>
<body>
<h2>Output</h2>
<p id="Output"></p>
<script>
var nestedObject = [
{
itemId: 1,
itemDetails: {
name: "C",
caregory: "Programming Language",
price: 500,
},
itemCategory: "Basic",
},
{
itemId: 2,
itemDetails: {
name: "C++",
caregory: "Programming Language",
price: 700,
},
itemCategory: "Beginner",
},
{
itemId: 1,
itemDetails: {
name: "Java Script",
caregory: "Web Development",
price: 1500,
},
itemCategory: "Advanced",
}]
let itemNames = nestedObject.filter(
eachObj => eachObj.itemDetails.price === 1500);
document.getElementById("Output").innerHTML
= JSON.stringify(itemNames);
</script>
</body>
</html>
Output:

Method 2: Using some() method
Example: This approach uses some() method to filter the nested objects. The some() method tests whether at least one element in the array passes the test implemented by the provided function. It returns a Boolean value.
<!DOCTYPE html>
<html>
<body>
<h2>Output</h2>
<p id="Output"></p>
<script>
const fruitData = [
{
name: "Apples",
details: [
{
fruitId: '1',
gradingDetails: [{ grade: 'A' }]
},
{
fruitId: '2',
gradingDetails: [{ grade: 'B' }]
}
]
},
{
name: "Oranges",
details: [
{
fruitId: '3',
gradingDetails: [{ grade: 'B' }]
},
{
fruitId: '4',
gradingDetails: [{ grade: 'D' }]
}
]
},
];
let output = fruitData.filter(eachVal => {
let opt = eachVal.details.some((
{ gradingDetails }) => gradingDetails
.some(({ grade }) => grade === 'A'));
return opt;
})
console.log(output);
document.getElementById("Output").innerHTML =
JSON.stringify(output);
</script>
</body>
</html>
Output:
