Filtering an array of objects based on a specific object in JavaScript

Hey there! Can you help me figure out how to iterate over an array using values from an object as filters?

const hotels = [
  {
    name: "Marina Inn",
    country: "USA",
    address: "Faliraki",
    stars: 4,  
  },    
  {
    name: "Mondrian Suites",
    country: "Greece",
    address: "Rhodes",
    stars: 5,
  },
  {
    name: "Mondrian Suites",
    country: "USA",
    address: "Rhodes",
    stars: 5,
  }      
]

I need to filter these objects based on the following criteria stored in an object:

const objFilter = {     
  country: "USA",      
  stars: 5,      
}

The expected result should be an array as shown below

[
  {
    name: "Mondrian Suites",
    country: "USA",
    address: "Rhodes",
    stars: 5,
  }      
]

Answer №1

If you need to extract the pairs of the filter object, you can utilize Object#entries.

After that, by employing Array#filter, you can loop through the array and fetch the corresponding elements using Array#every:

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

const 
  products = [{ name: "Widget", price: 20 }, { name: "Gadget", price: 30 }, { name: "Toy", price: 10 }],
  criteria = { price: 30 };
console.log( sortArrayByCriteria(products, criteria) );

Answer №2

To filter through hotels, you can use a for loop to check if each hotel has the specific values you are looking for. Here is an example code snippet:

var filter = {     
      country: USA,      
      stars: 5,      
    {

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

Answer №3

   const hotels = [
          {
            name: "Seaside Resort",
            country: "USA",address: "Miami Beach",
            stars: 4
          },
          {
            name: "Royal Oasis",
            country: "Greece",
            address: "Santorini",
            stars: 5,
            
          },
          {
            name: "Paradise Inn",
            country: "USA",
            address: "Hawaii",
            stars: 5,
            
          }
        ]
            
    const filteredHotels = hotels.filter(hotel=>hotel.country =='USA'&&hotel.stars==5);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve a collection of JSON objects using RestAngular

Currently, I am attempting to retrieve a JSON response from the server using Restangular. var baseAccounts = Restangular.one('getAllCustomers'); baseAccounts.getList().then(function(customers) { $scope.myData = customers; console. ...

Optimizing Array Comparison in JavaScript and Angular 2

In my Angular 2 .ts (TypeScript) file, I have declared two arrays as shown below: parentArray: Array<Model> initialized with {a, b, c, d} modifiedArray: Array<Model> modified with data {c, e, f, g} How can I efficiently determine the differ ...

The powerful combination of AJAX and the onbeforeunload event

I am working with an aspx page that includes a javascript function window.onbeforeunload = confirmExit; function confirmExit() { return "You have tried to navigate away from this page. If you made changes without clicking Submit, they will be lost. Are yo ...

developing a monorepo without utilizing a package registry and installing through Bitbucket

My organization is working on creating a monorepo for react components to be used across multiple sites. Currently, we have a repository called react-components on bitbucket and we are looking to convert it into a monorepo using lerna.js, with a structure ...

How can you merge webSDK with jQuery within a Vue Component?

I am currently working on incorporating the webSDK found at into our Vue application. My goal is to load jquery only within a single component. Below is the code I have written, however, when I click the button, it does not seem to function as expected. ...

Uploading a collection of objects to Node.js for storage in a database with Mongoose

I have developed a ReactJS form that allows users to dynamically add form "parts" (sections with form input fields). Let me illustrate this concept with an example: <div> <input placeholder="Author" /> <input placeholder="Age" /> ...

What could be causing the user object to be undefined in the NextAuth session callback function?

I'm experiencing an issue with NextAuth while trying to implement signIn with Discord provider. My goal is to add the userID into the session object using the session callback, but I keep encountering an error message stating: [next-auth][error][JWT ...

Encountering the "Not all code paths return a value" TypeScript error when attempting to manipulate a response before returning it, however, returning the response directly works without any issues

Encountering an issue where manipulating/process response and return triggers an error in TypeScript with the message "Not all code paths return a value.". Data is fetched from a backend API using RxJS lastValueFrom operator, along with lodash functions as ...

Arranging an array according to the values of another array in PHP

An array contains the following values: $Array1 = array("myfirst_value", "mysecond_value", "mythird_value"} Another array has random listings like this: $Array2 = array ( [4] => myfirst_value [8] => myforth_value [21] => mysecond_va ...

What is the process for exporting an NPM module for use without specifying the package name?

I am looking for a way to export an NPM module so that it can be used without specifying the package name. Traditionally, modules are exported like this: function hello(){ console.log("hello"); } module.exports.hello = hello; And then imported and ...

Display information using AngularJS within the Ionic framework

I am attempting to display a variable that is within a for loop. Here is my code where I store the value of $scope.datosTuto[i].Nombre in a variable. When I use an alert to print $scope.NombTuto, I can see the data but I want to display it on my HTML page. ...

Using Angular to send JSON data to an API

I'm attempting to send JSON data to an API, but I'm encountering the following error... 405 (Method Not Allowed) Below is the JSON object I'm trying to send and the corresponding HTTP request... var productAttributes = { "CostRequire ...

Is there a way to convert various elements sharing the same class into a list of array items?

Essentially, I am dealing with multiple elements sharing the same class name. My goal is to retrieve an array of integers from an API and then iterate through each element with this class name, replacing them with elements from the array sequentially. For ...

Browser refresh not triggering view update in Rails and ReactJS application

Recently, I integrated Reactjs into my Rails application. Strangely, when I modify the content of a .jsx file and reload it with different text, such as changing from <h1>Hello<h1/> to <h1> Hello again<h1/>, the browser fails to res ...

Is it just me or is one of these pieces of javascript not functioning properly?

I set out to develop a checklist that would automatically adjust a slider as users interacted with checkboxes. After some research, I stumbled upon the following two code snippets: http://jsfiddle.net/t2nvft7q/ $(document).on('click', '.ch ...

Need help speeding up website load times?

My website is loading incredibly slow, even though it has minimal content. I suspect that the high number of images and JavaScript elements on the page are contributing to this issue. Is there a method available to diagnose what exactly is causing the ext ...

Excessive JSON formatting is consuming an excessive amount of storage space

As I work on developing a website that recommends locations to visit in NYC, I am facing an issue with saving JSON data in local storage. My goal is to allow users to add their own suggestions and eventually integrate MongoDB into the site. To build the si ...

Verify the presence of data in Firebase using Angular

Currently, I am working on a web project that involves Angular connected with Firebase console. In my service class, I have defined a function to verify if a certain value exists in the database before saving it. However, whenever I call this function in m ...

unable to detect image input type

My dilemma lies in trying to submit a form using an image input type. The ajax request works as expected, and I receive a response from my php script. However, I encountered an issue where the image button was not changing its image upon submission. Accord ...

C# Custom Array Data Grouping

I'm having difficulty organizing some data into an array with a specific structure: http://pastebin.com/dxkCnzq3 To provide more clarification, the format I'm trying to achieve is something like this (number of type) new Array[Bool(2)][Bool(2 ...