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
>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)