0

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

   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

Allan Chua
  • 9,305
  • 9
  • 41
  • 61
HardRock
  • 809
  • 2
  • 12
  • 37
  • Why `.forEach()`? Have a look at its [documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) why that is the wrong tool. – Andreas Jan 20 '22 at 08:24
  • You probably want to use something like [`Array.every`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every) instead of `forEach` – derpirscher Jan 20 '22 at 08:28

3 Answers3

2

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)
Saeed Shamloo
  • 6,199
  • 1
  • 7
  • 18
0

Assuming that open and close are always equal or bigger than 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)
Alan Omar
  • 4,023
  • 1
  • 9
  • 20
  • while this will work for that special case it's not very flexible. Ie the states which to look for are hardcoded and cannot be configured via the input array ... – derpirscher Jan 20 '22 at 08:30
-2

Try this approach:

const opened = data.filter((item) => item.status.open === 1);

you can add your own checking inside filter. it will return an array with found object.

Paiman Rasoli
  • 1,088
  • 1
  • 5
  • 15