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