Filter an array of objects based on a provided array

I have an array of objects that I need to filter based on their statuses.

const data = [
{
     id:1,
     name:"data1",
     status: {
          open:1,
          closed:1,
          hold:0,
          block:1
     }
},
{
     id:2,
     name:"data2",
     status: {
          open:1,
          closed:0,
          hold:4,
          block:1
     }
},
{
     id:3,
     name:"data3",
     status: {
          open:0,
          closed:0,
          hold:4,
          block:0
    }
}
]

The statuses are defined in an array like this:

const statuses = ['open','closed']

I want to filter all data that contains the status "open" and "closed" with a value greater than 0. The expected result should be:

   const result = [
    {
       id:1,
       name:"data1",
       status: {
              open:1,
              closed:1,
              hold:0,
              block:1
        }
    }]

Here is my attempt at filtering the data:

const result = data.filter(item => {
            return (
                statuses.forEach(val => {
                    if (item.status[val] > 0)
                        return item   
                })
            )
        })

I'm sure I'm missing something in my code, so any help would be greatly appreciated. Thank you.

Answer №1

To reach your objective, you can utilize the every method instead of forEach, as shown in the following code snippet:

const information = [ { id:1, name:"info1", status: { open:1, closed:1, hold:0, block:1 } }, { id:2, name:"info2", status: { open:1, closed:0, hold:4, block:1 } }, { id:3, name:"info3", status: { open:0, closed:0, hold:4, block:0 } } ];
const states = ['open','closed'];

const output = information.filter( ({status}) => states.every(key => status[key] > 0) );

console.log(output)

Answer №2

When open and close values are assumed to always be greater than or equal to 0:

const data=[{id:1,name:"data1",status:{open:1,closed:1,hold:0,block:1}},{id:2,name:"data2",status:{open:1,closed:0,hold:4,block:1}},{id:3,name:"data3",status:{open:0,closed:0,hold:4,block:0}}];

let result = data.filter(e => e.status.open && e.status.closed)

console.log(result)

Answer №3

Give this method a shot:

const activated = data.filter((item) => item.state.active === true);

Feel free to customize the filter function to suit your needs. The result will be an array containing the matching objects.

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

Guide on plotting latitude and longitude coordinates on Google Maps with Vue.js through JSON data fetched via AJAX

I have implemented a Vue.js script to fetch JSON data through an AJAX request. However, I am encountering issues with the code. <script> new Vue({ el: '#feed' , data: { details: [], }, mounted() { this.$nextTick(fu ...

Why do some developers choose to use the underscore prefix in React/React-native function names?

Traditionally, in JavaScript, I would prefix "private" function names with an underscore (_) due to the lack of access modifiers. However, I find myself a bit puzzled when working on a class in languages like C++ or Java that has two functions: one for int ...

Establishing communication between a master process and worker processes in Node.js: A guide to verifying bidirectional communication

After coming across this particular script from the node documentation, I tried to implement it for sending messages between Master and worker processes using cluster. However, upon running the script, I encountered an issue where I could not verify the me ...

Issue with Angular dropdown menu not showing the initial option

I am trying to set up a drop-down menu with the first item in the list appearing after it has been sorted by 'name' using the code snippet below: <h2 class="presentation site is-input-header">Site</h2> <div class="modal-select-ele ...

What steps can I take to resolve this error when utilizing an npm package in client-side JavaScript?

Just when I thought I was getting the hang of socket.io, I hit a roadblock on the client side. Following my instructor's advice, I installed socket.io-client package for my project. But when I tried to use it in my client-side JS code, I encountered a ...

Unable to make a successful POST request using the JQuery $.ajax() function

I am currently working with the following HTML code: <select id="options" title="prd_name1" name="options" onblur="getpricefromselect(this);" onchange="getpricefromselect(this);"></select> along with an: <input type="text" id="prd_price" ...

Ways to differentiate between an angular element and a jQuery element

In order to implement a feature where clicking outside of a dropdown hides it within a directive, I have the following code: $(document).click(function(e) { var selector = $(e.target).closest('.time-selector'); if (!selector. ...

Exploring Angular 6 with Universal Karma for effective module testing

Issue I have been facing challenges while testing my Angular 6 application with Karma. I am encountering errors such as: Can't bind to 'ngModel' since it isn't a known property of 'mat-select'. Although the import works in ...

When debugging in ASP MVC4, JavaScript will only evaluate HiddenFor once you've paused to inspect it

Struggling with evaluating a hidden field in JavaScript (ASP MVC4). I've set up a model in my View with a hidden input for one of the properties. @Html.HiddenFor(mdl => mdl.FilterByUser, new { @id = "filterByUserId" }) Within my Helper, I have a ...

The Material UI Icon is missing from the location '@mui/icons-material/Send.js'

I am currently utilizing the Material UI library and attempting to import SendIcon through this import statement: import { SendIcon } from "@mui/icons-material/Send.js"; Due to including "type" : "module" in my package.json f ...

What are the benefits of using React.useMemo or React.useCallback within component props?

Exploring efficient ways to implement TailwindCSS in React, considering its utility-first nature leading to component-heavy code (e.g. className="w-full bg-red-500"). One approach is creating a utility function like: utils/tailwind.ts const tw = (...clas ...

When I type in the TextBox, the CheckBox value should be deactivated if it is unchecked

Whenever I attempt to input text into the textbox associated with my checkbox, the checkbox automatically becomes unchecked. How can I prevent this from happening? <span id="TRAVEL_TYPE_1"><input id="TRAVEL_TYPE_0" type="checkbox" onclick="Update ...

Prevent elements from displaying until Masonry has been properly set up

My goal is to merge Masonry elements with existing ones. Currently, the items appear before Masonry initializes then quickly adjust into position a moment later. I want them to remain hidden until they are in their proper place. This is the snippet (with ...

Developing advanced generic functions in Typescript

I am currently working on a Hash Table implementation in Typescript with two separate functions, one to retrieve all keys and another to retrieve all values. Here is the code snippet I have so far: public values() { let values = new Array<T>() ...

Using JSON files in React applications is essential for accessing and displaying static data. Let's

If I want to refer to a file locally in my JS code instead of on a remote server, how can I do that? I know the file needs to be in the public folder, but I'm unsure how to reference it in the JavaScript provided above. class App extends Component { c ...

Anticipating the resolution of promises and observables in Angular 2

Within my accountService module, there is a dialog prompt that requests the user's username and password, returning a promise. If the user clicks on close instead of dismissing the dialog box and the validators require the input data before allowing t ...

What is the best way to compare two sets of arrays and generate a new one with unique key-value pairs?

I have two arrays and I want to extract specific key-value pairs from each and combine them into a new array, handling duplicate entries. First Array : [ {id: 2, name: "HSBC", status: "YES"}, {id: 3, name: "Morgan Stanley&quo ...

PHP-based user interface queue system

I am in the process of developing a website that enables users to manipulate a webcam by moving it from left to right. Each user will have a one-minute window to control the camera. I plan on implementing a queuing system on the site to ensure that users ...

Dealing with browser timeouts for HTTP requests using JavaScript

Managing time out situations in a web application when calling a REST API is crucial. Below is the code snippet I am using to make the API call with jQuery ajax. $.ajax({ type: "POST", url: endpoint, data: payload, ...

Utilizing variable index to access nested objects

When my Ajax request returns a response, the data takes the form of an object shown below: https://i.sstatic.net/wA2Px.png How can I access the value? Keep in mind that idVariable is a variable. data.test1.idVariable.test2.value The result of the code ...