How to filter an object depending on the field's value in JavaScript?


Overview

An object in JavaScript is defined as a set of key−value pairs. It is used to define the properties of a single object. So to filter the object depending on the field's value can be achieved using JavaScript. By using the if−else condition we can filter the object depending on the value. So to filter from the object, first we have access to the key from the object, so for this we should have some prior knowledge of the object and its manipulation. As the manipulation of the object plays an important role in filtering the field value of the object.

Syntax

The Syntax to filter the object using value is shown below.

array.filter((p) => {
   if (p.field == fieldValue) {
      newArray.push(p)
   }
})
  • array − An array on the above Syntax is termed as a collection of the objects.

  • filter() − A filter is a JavaScript method which takes the array as input to the filter and filters the elements on the basis of certain conditions.

  • p − 'p' is the reference parameter passed to the filtered function.

  • p.field − Using this we can access any field in the object of the name 'p'.

  • fieldValue − In the above Syntax 'fieldValue' is termed as the value which we have to find in the JavaScript object.

  • newArray − It is a reference of an array which will consist of the filtered object.

  • push() − It is a JavaScript method of an array which is used to insert the elements in an array. The push() method inserts the element to the last of an array.

Algorithm

  • Step 1 − Create a HTML file on your text editor and add a HTML boilerplate to the file.

  • Step 2 − Now create a parent div container which contains the rendered key value from the objects.

  • Step 3 − Now add an input tag to the container of type text with an id attribute of name as "inpVal".

<input type="text" placeholder="Filter by brand" id="inpVal">
  • Step 4 − Now add a HTML button with an onclick event handler as "fil()".

<button onclick="fil()">Filter</button>
  • Step 5 − Now add a HTML table to the div container with the id name in <tbody> attribute as "ans".

<table border style="text-align: center;">
   <thead>
      <th>Id</th>
      <th>ProductName</th>
      <th>Brand</th>
   </thead>
   <tbody id="ans"></tbody>
</table>
  • Step 6 − Now create another div container for the Output of the filtered object as field value.

  • Step 7 − Now create a table which will render the filtered object.

<div>
   <table border="" style="text-align: center;">
      <thead>
         <th>Id</th>
         <th>ProductName</th>
         <th>Brand</th>
      </thead>
      <tbody id="ans2">
         <td>-</td>
         <td>-</td>
         <td>-</td>
      </tbody>
   </table>
</div>
  • Step 8 − Now add a script tag to the body of the file.

<script></script>
  • Step 9 − Now create an empty variable and an array which contains some sample value in the object.

var t = '';
var obj = [
   { ID: 1, ProductName: 'Mobile', brand: 'Samsung' },
   { ID: 2, ProductName: 'Acessories', brand: 'Samsung' },
   { ID: 3, ProductName: 'Processor', brand: 'AMD' },
   { ID: 4, ProductName: 'SSD', brand: 'Samsung' }
];
  • Step 10 − Now use a for loop to iterate on the array and use the object access Syntax to access the object and render to the table.

for (let index = 0; index < obj.length; index++) {
   t += `
   <tr>
      <td>`+ obj[index].ID + `</td>
      <td>`+ obj[index].ProductName + `</td>
      <td>`+ obj[index].brand + `</td>
   </tr>
   `
}
  • Step 11 − Now use the DOM innerHTML method to add the object key−value to the table.

document.getElementById("ans").innerHTML = t;
  • Step 12 − Now create an arrow function as file().

fil = () => {}
  • Step 13 − Store the value of the input tag in the reference variable.

var f = ``
var iVal = document.getElementById("inpVal").value;
  • Step 14 − Now use the Syntax to find the filtered value from the object.

obj.filter((p) => {
   if (p.brand == iVal) {
      filteredArray.push(p)
   }else{
      f="No result found";
   }              
})
  • Step 15 − Create an empty array.

var filteredArray = [];
  • Step 16 − Now use forEach to display the Output stored in an filteredArray.

filteredArray.forEach(element => {
   f += `
   <tr>
      <td>`+ element.ID + `</td>
      <td>`+ element.ProductName + `</td>
      <td>`+ element.brand + `</td>
   </tr>
   `
});
  • Step 17 − Use the HTML DOM property to insert the HTML data to the table.

document.getElementById("ans2").innerHTML = f;

Example

In this Example we will be rendering the objects data from the JavaScript object to the HTML table, will also add the HTML input tag to filter the given object depending on the field's value.

<html>
<head>
   <title> filter object depending on field value </title>
</head>
<body>
   <div>
      <h3> object rendered table (Search is case sensitive) </h3>
      <input type="text" placeholder="Filter by brand" id="inpVal">
      <button onclick="fil()">Filter</button>
      <table border style="text-align: center;">
         <thead>
            <th>Id</th>
            <th>ProductName</th>
            <th>Brand</th>
         </thead>
         <tbody id="ans"></tbody>
      </table>
   </div>
   <hr>
   <div>
      <h3>Filtered object depending on brand field value</h3>
      <table border="" style="text-align: center;">
         <thead>
            <th>Id</th>
            <th>ProductName</th>
            <th>Brand</th>
         </thead>
         <tbody id="ans2">
            <td>-</td>
            <td>-</td>
            <td>-</td>
         </tbody>
      </table>
   </div>
   <script>
      var t = '';

      var obj = [
         { ID: 1, ProductName: 'Mobile', brand: 'Samsung' },
         { ID: 2, ProductName: 'Acessories', brand: 'Samsung' },
         { ID: 3, ProductName: 'Processor', brand: 'AMD' },
         { ID: 4, ProductName: 'SSD', brand: 'Samsung' }
      ];

      for (let index = 0; index < obj.length; index++) {
         t += `
         <tr>
            <td>`+ obj[index].ID + `</td>
            <td>`+ obj[index].ProductName + `</td>
            <td>`+ obj[index].brand + `</td>
         </tr>
         `
      }

      document.getElementById("ans").innerHTML = t;

      fil = () => {
         var filteredArray = [];
         var f = ``
         var iVal = document.getElementById("inpVal").value;

         obj.filter((p) => {
            if (p.brand == iVal) {
               filteredArray.push(p)
            }else{
               f="No result found";
            }             
         })
                     
         filteredArray.forEach(element => {
            f += `
            <tr>
               <td>`+ element.ID + `</td>
               <td>`+ element.ProductName + `</td>
               <td>`+ element.brand + `</td>
            </tr>
            `
         });
         document.getElementById("ans2").innerHTML = f;
      }
   </script>
</body>
</html>

The below images show the Output of the above feature on the basis of their different phases. So in the first image it shows a simple layout of the web page which contains a search box to filter the object by value and a table which is the data of the object which will be filtered. So when a user types a brand name to the search field and hits the filter button. The user gets all the filtered rows from the object depending on its value. As in the second and third image we can see that when a user types in the brand value as "Samsung" or "AMD", he gets the filtered data in the form of a new table.

In the last image we can see that when a user types in the value to the search field which is not in the object, then a user will get an Output as "No result found".

Conclusion

This feature is used by the ecommerce web applications, these applications filter their data on the basis of the user input as some conditions such as rating, pricing or the quality of the product. We can also use this feature in the Contact management system or employee management system to filter out the details. This can be integrated to filter the data from the real time API.

Updated on: 13-Oct-2023

85 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements