Home > database >  How to do complex conditional filtering in Javascript?
How to do complex conditional filtering in Javascript?

Time:10-27

So I want to filter an array of objects according to a few filters I have created:

items.filter(
    (obj) =>
    (!status || (obj.globalId && obj.globalId !== "")) &&
    (!deletedSwitch || obj.deleted === deletedSwitch) &&
    (!filteredUsername || obj.userId === userId) &&
    (!filteredType || obj.type === filteredType) &&
    (!filteredVariety || obj.variety === filteredVariety) &&
    (!filteredSize || parseInt(obj.size) === filteredSize)
)

So as you can see, I filter the items based on a few properties. These properties are selected through a <select> component. status property used to be a boolean state where I want to check if the item has a globalId or not. However, now I want to change it in a way where I check if status is connected, then I want to filter all items that have a globalId each. But if the status is not connected, I want to filter all items that DO NOT have a globalId. How can I modify my code above to achieve this?

CodePudding user response:

Just add it with OR?

items.filter(obj =>
    ((status === "connected" && obj.globalId && obj.globalId !== "") ||
     (status === "not connected" && !obj.globalId)) &&
    (!deletedSwitch || obj.deleted === deletedSwitch) &&
    (!filteredUsername || obj.userId === userId) &&
    (!filteredType || obj.type === filteredType) &&
    (!filteredVariety || obj.variety === filteredVariety) &&
    (!filteredSize || parseInt(obj.size) === filteredSize)

CodePudding user response:

How about using a ternary (conditional expression)?

(status == "connected" ?
 object.globalId && obj.globalId !== "" :
 !object.globalId)

Or, if you anticipate having more status values in the future, using an object is more extensible (and it's arguably more readable in any case):

({
    "connected": object.globalId && obj.globalId !== "",
    "not connected": !object.globalId,
}[status])
  • Related