简体   繁体   中英

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,
  }      
]

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) );

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);
  }
});
   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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM