Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter array of objects by given array

I have array of objects in which I need to filter by 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
    }
}
]

statuses are in array

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

I would need to filter all data that contains status open and closed bigger than 0.
So result would be

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

This is my attempt,

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

I’m sure I’m missing something here and I would appreciate any kind of help.
Thank you

>Solution :

You can acheive your goal by using every method instead of forEach, like this:

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 } } ];
const statuses = ['open','closed'];

const result = data.filter( ({status}) => statuses.every(key => status[key] > 0) );

console.log(result)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading