Oleksii Zelenko
Oleksii Zelenko

Reputation: 2701

How to filter array of objects by object in JS

Good day. Tell me how can I iterate over an array taking values for filters from an object?

const hotels = [
  {
    name: "Marina Inn",
    country: "США"
    address: "Фалираки",
    stars: 4,  
  },    
  {
    name: "Mondrian Suites",
    country: "Греция",
    address: "Родос",
    stars: 5,
  },
  {
    name: "Mondrian Suites",
    country: "США",
    address: "Родос",
    stars: 5,
  }      
]

I want to filter objects by filters from object:

const objFilter = {     
  country: "США",      
  stars: 5,      
}

You should get an array

[
  {
    name: "Mondrian Suites",
    country: "США",
    address: "Родос",
    stars: 5,
  }      
]

Upvotes: 2

Views: 259

Answers (3)

Majed Badawi
Majed Badawi

Reputation: 28434

You can use Object#entries to get the pairs of the filter object.

Then, using Array#filter, iterate over the array and return the matching elements using Array#every:

const filterArrByObj = (arr = [], obj = {}) => {
  const filterEntries = Object.entries(obj);
  return arr.filter(e =>
    filterEntries.every(([key, value]) => e[key] === value)
  );
}

const 
  hotels = [{ name: "Marina Inn", country: "США", address: "Фалираки", stars: 4 }, { name: "Mondrian Suites", country: "Греция", address: "Родос", stars: 5 }, { name: "Mondrian Suites", country: "США", address: "Родос", stars: 5 }],
  objFilter = { country: "США", stars: 5 };
console.log( filterArrByObj(hotels, objFilter) );

Upvotes: 4

Oleg Levin
Oleg Levin

Reputation: 3621

   const hotels = [
          {
            name: "Marina Inn",
            country: "США",address: "Фалираки",
            stars: 4
          },
          {
            name: "Mondrian Suites",
            country: "Греция",
            address: "Родос",
            stars: 5,
            
          },
          {
            name: "Mondrian Suites",
            country: "США",
            address: "Родос",
            stars: 5,
            
          }
        ]
            
    const results = hotels.filter(hotel=>hotel.country =='США'&&hotel.stars==5);

Upvotes: 0

Het Delwadiya
Het Delwadiya

Reputation: 119

Use for loop and check if object has the values you want like - (Note: New to JS, didn't tried but hope it works)

var filter = {     
      country: США,      
      stars: 5,      
    {

hotels.forEach(function(hotel){
  if(hotel.country == filter.country && hotel.stars == filter.stars) {
      console.log(hotel);
  }
});

Upvotes: 0

Related Questions