Reputation: 1279
I have this array burgerActions
:
[
{
statusId: 2,
label: 'Accept'
},
{
statusId: 3,
label: 'Reject'
},
{
label: 'Consult'
},
{
label: 'Transfer'
}
]
and this object status
which can be either :
{
"label": "Accept",
"id": 2
}
or :
{
"label": "Reject",
"id": 3
}
In a first case you have to create a new array from burgerActions
array where the statusId
is not equivalent to the id of the status
object that we have (we can only have one status
object of the 2 cases that I listed).
For that I used the filter
method :
const result = burgerActions.filter((element) => {
return element.statusId !== recommendation.status.id
})
In the second case I need a complex conditioning adding with boolean
const statusRef = recommendation.recipient
In a first case I want if statusRef
is false
filter the last object in the burgerAction
({label: 'Transfer'}
) but not in the case if statusRef
is true.
I need a method that does this type of filter without using the if ()
conditions because there are several cases to handle.
Upvotes: 2
Views: 117
Reputation: 32145
If you want to filter the objects that doesn't have the same statusId
as in the recommendation.status.id
and if recommendation.recipient === true
filter the ones that doesn't have statusId
, you can use this condition in the filter callback function:
element.statusId !== recommendation.status.id && recommendation.recipient ? element.statusId != null : true;
Where && recommendation.recipient ? element.statusId != null : true
means that if recommendation.recipient
is true
filter elements with a statusId
.
Here's how should be your code:
var recommendation = {
status: {
"label": "Pending",
"id": 1
},
recipient: true
};
const result = burgerActions.filter((element) => {
return element.statusId !== recommendation.status.id && recommendation.recipient ? element.statusId != null : true;
});
Demo:
var burgerActions = [{
statusId: 2,
label: 'Accept'
},
{
statusId: 3,
label: 'Reject'
},
{
label: 'Consult'
},
{
statusId: 1,
label: 'Transfer'
}
];
var recommendation = {
status: {
"label": "Pending",
"id": 1
},
recipient: true
};
const result = burgerActions.filter((element) => {
return element.statusId !== recommendation.status.id && recommendation.recipient ? element.statusId != null : true;
});
console.log(result);
Upvotes: 1