Sort through a JavaScript array based on an object that holds a limited number of the array's properties

Is there a way to efficiently find matching items in an array of objects using a filter object that only includes a subset of the array properties? For instance, consider a customer:

let Customer = {
    Name: "John Doe",
    Age: 80,
    Hair: "Red",
    Gender: "Male",
};

Let's say we have a search object:

let searchObject ={
    Hair: "Red",
    Gender: "Male"
}

Instead of manually filtering the array like this:

this.array.filter(z=>z.Hair == searchObject.Hair && z.Gender == searchObject.Gender);

It would be great if the filter automatically adjusts when more properties are added to the searchObject.

Answer №1

You can utilize the every() method on the Object.keys() of the searchObject to check if all the values of keys in the searchObject match with the corresponding values in an array of objects.

Here is an example with two objects that have different Gender:

let array = [{
    Name: "John Doe",
    Age: 80,
    Hair: "Red",
    Gender: "Male",
}, {
    Name: "Marry",
    Age: 80,
    Hair: "Red",
    Gender: "Female",
}]

let searchObject = {
    Hair: "Red",
    Gender: "Male"
}

const res = array.filter(x => Object.keys(searchObject).every(k => x[k] === searchObject[k]));

console.log(res)

Answer №2

To sort through the data, you can use key/value pairs as filters.

var users = [{ Name: "Jane Smith", Age: 35, Hair: "Blonde", Gender: "Female" }],
    filterObject = { Hair: "Blonde", Gender: "Female" },
    filter = Object.entries(filterObject),
    results = users.filter(obj => filter.every(([key, value]) => obj[key] === value));

console.log(results);

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

Closing a Javascript Websocket connection may result in server crash

I encountered an issue while trying to exchange data between my client and server. It seems that every time I closed my client, the server crashed... My server runs on Node.JS using the nodejs-websocket library. After some investigation, I discovered tha ...

Sending information across React context

I've encountered a challenge when trying to transfer data from one context to another in React. The job data I receive from a SignalR connection needs to be passed to a specific job context, but I'm unsure of the best approach for achieving this. ...

Updating the Keycloak token in VueJS using keycloak-js even when it is still valid

I have implemented a VueJS frontend connected to Keycloak using keycloak-js openid, without using the implicit flow https://i.sstatic.net/BxhJh.png Currently, there is a scenario in which the Backend NodeJS adds groups to a user in Keycloak. However, in ...

Troubleshooting issue with applying hover effect to child divs

How come when I hover over one of the child items in my parentDiv, the background of the last childDiv changes no matter which child I place my mouse on? for (let i = 0; i < Number(height); i++) { for (let j = 0; j < Number(width); j++ ...

Manipulate an object in Three.js using the ObjLoader functionality

I'm currently working on manipulating an object loaded using OBJLoader in Three.js. The issue I'm facing is that while it's easy to manipulate the object once, I can't figure out how to do so during the animate loop or anywhere outside ...

Angular 5, utilizing rxjs to map to JSON, encountered an issue where 'json' is not recognized on the type 'object'

Having trouble following an online video tutorial on Angular, none of the other solutions seem to be working for me. https://i.sstatic.net/KMNT4.png import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/co ...

how to prevent autoscrolling in an angular application when overflow-x is set to

In my socket event, I am using $scope.items.unshift(item) to place the new item at the top of the list. The html code includes <ol ng-repeat="item in items"><li>{{item.name}}</li></ol> An issue arises when a new item is added whil ...

Having trouble uploading an image to firebase storage as I continuously encounter the error message: Unable to access property 'name' of undefined

Hey there, I'm currently facing an issue while trying to upload an image to Firebase storage. Despite following all the instructions on the official Firebase site, I'm stuck trying to resolve this error: Uncaught TypeError: Cannot read property ...

The HTML document is having trouble establishing a connection with socketio

I currently hold an HTML file within my local file system, presented as follows: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Example of a Minimal Working File</title> ...

Implementing custom CSS styles for HighCharts API pie chart drilldown labels

I successfully created a pie chart using highcharts and configured the chart with the following options: chart: { type: 'pie', }, In order to change the width of the text on the chart, I added the following options which force e ...

Angular 8 mat-sort issue: malfunctioning sort functionality

I have successfully implemented sorting in a mat-table within an angular 8 project. While referring to the guide available at https://material.angular.io/components/sort/overview, I encountered an issue where the sorting functionality is only working for s ...

Retrieving selected options from a jQuery mobile multiselect for database storage

I'm currently working on extracting values from a select list in a jQuery mobile application. Here's the markup for my select element: <div data-role="fieldcontain"> <label for="stuff" class="select">Stuff:</label ...

Exploring the capabilities of extending angular components through multiple inheritance

Two base classes are defined as follows: export class EmployeeSearch(){ constructor( public employeeService: EmployeeService, public mobileFormatPipe: MobileFormatPipe ) searchEmployeeById(); searchEmployeeByName(); } ...

Is the Order of a JSON Array Dependable?

When working with JSON, it's clear that relying on the ordering of key-value pairs may not be reliable. For instance, a JSON parser could interpret { "someKey" : "someValue", "anotherKey" : "anotherValue", "evenAnotherKey" : "evenAnotherV ...

Using a foolproof method to accurately track views on stored static pages

I'm trying to find a way to accurately count pageviews on cached pages asynchronously. Due to high traffic, I am generating static HTML pages that are served directly by the web server without requiring PHP or database connections. The issue lies in ...

manipulating elements of an array within a .map method

i am stuck with a json exporting database. it generates json data in the following format. {"Drinks":[ { "name":"name", "discription":"discription", "image":"image", "ingredients&qu ...

Using Typescript in conjunction with nodemon and VS Code for seamless integration of declaration merging

After adding a middleware to my express app app.use(function(req: express.Request, res: express.Response, next: express.NextFunction) { req.rawBody = 'hello2'; next(); }); I also included custom.d.ts declare namespace Express { expor ...

Step-by-step guide on importing popper.js

While it may seem like a simple question, I am struggling to find the answer. How can I import popper.js that comes with Bootstrap 4 beta? I am using Bower and have successfully installed Bootstrap 4 beta. However, in the bower_components folder, there is ...

Adjusting the speed of Flexslider with mousewheel control

I am looking to implement flexslider with mousewheel functionality. Here is an example of how I want it to work: $('#slider').flexslider({ animation: "slide", mousewheel: true, direction: "vertical", ...

What is the reasoning behind referring to RxJS Subject as Multicast and Observable as Unicast?

I've been delving into RxJS for a while now and I'm struggling to grasp why we refer to RxJS Subject as Multicast and Observable as Unicast. I understand that Subject can emit data using next(), and like a regular Observable, we can subscribe to ...