Filter an Array of Objects in React

0
13


Views:
6

Filter with 1 condition

export default function App() 
  const employees = [
     id: 1, name: "A", country: "India" ,
     id: 2, name: "B", country: "Belgium" ,
     id: 3, name: "C", country: "India" ,
     id: 4, name: "D", country: "Germany" 
  ];

  // ️ filter with 1 condition
  const filtered = employees.filter((employee) => 
    return employee.country === "India";
  );

  return (
    <div>
      filtered.map((employee) => 
        return (
          <div key=employee.id>
            <h2>name: employee.name</h2>
            <h2>country: employee.country</h2>

            <hr />
          </div>
        );
      )
    </div>
  );

Filter with 2 conditions

export default function App() 
  const employees = [
     id: 1, name: "A", country: "India" ,
     id: 2, name: "B", country: "Belgium" ,
     id: 3, name: "C", country: "India" ,
     id: 4, name: "D", country: "Germany" 
  ];

  // ️ filter with 2 conditions
  const filtered = employees.filter(employee => 
    return employee.country === 'India' && employee.id === 3;
  );

  return (
    <div>
      filtered.map((employee) => 
        return (
          <div key=employee.id>
            <h2>name: employee.name</h2>
            <h2>country: employee.country</h2>

            <hr />
          </div>
        );
      )
    </div>
  );

Directly call the map() method after filtering.

export default function App() 
  const Data = [
     id: 1, name: "A", country: "India" ,
     id: 2, name: "B", country: "US" ,
     id: 3, name: "C", country: "Canada" ,
     id: 4, name: "D", country: "India" 
  ];

  return (
    <div>
      Data.filter((emp) => 
        return emp.country === "India";
      ).map((emp) => 
        return (
          <div key=emp.id>
            <h2>name: emp.name</h2>
            <h2>country: emp.country</h2>

            <hr />
          </div>
        );
      )
    </div>
  );

filter

Let us know if you liked the post. That’s the only way we can improve.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here