2

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

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.