Filtering JSON Data Based on Age in JavaScript

Filtering JSON Data Based on Age in JavaScript

Recently, I encountered a task where I needed to filter out data from an array of objects in JavaScript based on a specific condition. The goal was to extract only those objects where the age property was less than 26. Here, I’ll walk you through my solution step-by-step.

Problem Statement

Given an array of employee objects, each with name and age properties, I needed to filter out and display only those employees who were below 26 years of age.

Initial Array Structure

Below is the array of objects that served as my dataset:

let emp = [
    { name: 'abc', age: 30 },
    { name: 'xyz', age: 20 },
    { name: 'cde', age: 25 },
    { name: 'fgh', age: 28 }
];

Implementing the Filter Logic

To achieve this, I utilized JavaScript’s built-in filter() method. The filter() method creates a new array with all elements that pass the test implemented by the provided function. In my case, the condition was simply checking if age was less than 26:

const result = emp.filter((value) => {
    return value.age < 26;
});

console.log(result);

Explanation

  • emp.filter(): This method iterates over each object in the emp array.
  • Callback Function: For each object, the function checks if the age property is less than 26. If the condition evaluates to true, the object is included in the result array.
  • Output: The filtered array is logged to the console, showing only employees whose age is less than 26.

Dynamically Displaying the Filtered Results *result.map()

To dynamically display the filtered data in the DOM, I used the map() method to append the results to an HTML element:

result.map(data => appDiv.innerHTML += `<h1>${data.name} ${data.age}</h1>`);

result.map(): Iterates over the filtered result array and updates the innerHTML of an element (e.g., appDiv) by appending an h1 element containing the name and age of each object.

Output

When I ran this code, the output in the console was:

[
    { name: 'xyz', age: 20 },
    { name: 'cde', age: 25 }
]

As expected, only the objects where age was less than 26 were returned.

Scroll to Top